For this we will write directives
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 |
app.directive('validNumber', function () { // allow only number and decimal point return { require: '?ngModel', link: function (scope, element, attrs, ngModelCtrl) { if (!ngModelCtrl) { return; } ngModelCtrl.$parsers.push(function (val) { if (angular.isUndefined(val)) { var val = ''; } var clean = val.replace(/[^0-9\.]/g, ''); var decimalCheck = clean.split('.'); if (!angular.isUndefined(decimalCheck[1])) { decimalCheck[1] = decimalCheck[1].slice(0, 2); clean = decimalCheck[0] + '.' + decimalCheck[1]; } if (val !== clean) { ngModelCtrl.$setViewValue(clean); ngModelCtrl.$render(); } return clean; }); element.bind('keypress', function (event) { if (event.keyCode === 13) { event.preventDefault(); } }); } }; }); |
For use this add html like below
1 |
<input type='text' valid-number> |
If you have any doubt, then drop comment below. 🙂