01 Mar How to allow only numbers with or without decimal values in Angular.js
The code is pretty simple:
angular .module('MyApp') .directive('numbersOnly', numbersOnly)
function numbersOnly(){ return { require: 'ngModel', link: function(scope, element, attrs, modelCtrl) { modelCtrl.$parsers.push(function (inputValue) { if (inputValue == undefined) return '' var transformedInput = inputValue.replace(/[^\d]/g, ''); if (transformedInput!=inputValue) { modelCtrl.$setViewValue(transformedInput); modelCtrl.$render(); } return transformedInput; }); } }; }
if you want to accept decimals also just replace:
var transformedInput = inputValue.replace(/[^\d]/g, ''); //for var transformedInput = inputValue.replace(/[^-0-9\.]/g, '');
How to use it:
<input name="phone_number" numbers-only="" type="text">
No Comments