In angularjs is there any functionality available that allows only numbers to be typed into a text box like
Using <input type="number"> The standard solution to restrict a user to enter only numeric values is to use <input> elements of type number. It has built-in validation to reject non-numerical values.
The angular. isNumber() function in AngularJS is used to determine the parameter inside isNumber function is a number or not. It returns true if the reference is a number otherwise returns false.
This code shows the example how to prevent entering non digit symbols.
angular.module('app'). directive('onlyDigits', function () { return { restrict: 'A', require: '?ngModel', link: function (scope, element, attrs, modelCtrl) { modelCtrl.$parsers.push(function (inputValue) { if (inputValue == undefined) return ''; var transformedInput = inputValue.replace(/[^0-9]/g, ''); if (transformedInput !== inputValue) { modelCtrl.$setViewValue(transformedInput); modelCtrl.$render(); } return transformedInput; }); } }; });
HTML
<input type="text" name="number" only-digits>
// Just type 123
.directive('onlyDigits', function () { return { require: 'ngModel', restrict: 'A', link: function (scope, element, attr, ctrl) { function inputValue(val) { if (val) { var digits = val.replace(/[^0-9]/g, ''); if (digits !== val) { ctrl.$setViewValue(digits); ctrl.$render(); } return parseInt(digits,10); } return undefined; } ctrl.$parsers.push(inputValue); } }; });
// type: 123 or 123.45
.directive('onlyDigits', function () { return { require: 'ngModel', restrict: 'A', link: function (scope, element, attr, ctrl) { function inputValue(val) { if (val) { var digits = val.replace(/[^0-9.]/g, ''); if (digits.split('.').length > 2) { digits = digits.substring(0, digits.length - 1); } if (digits !== val) { ctrl.$setViewValue(digits); ctrl.$render(); } return parseFloat(digits); } return undefined; } ctrl.$parsers.push(inputValue); } }; });
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With