Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

angularjs: allows only numbers to be typed into a text box

In angularjs is there any functionality available that allows only numbers to be typed into a text box like

like image 406
Ali Hasan Avatar asked Apr 18 '13 19:04

Ali Hasan


People also ask

How do I put numbers only in a text box?

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.

Is Numeric in angular?

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.


2 Answers

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;             });         }     }; }); 
like image 83
Anton Avatar answered Oct 06 '22 00:10

Anton


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);       }     };  }); 
like image 42
My Mai Avatar answered Oct 05 '22 23:10

My Mai