Restrict input as numbers on input fields using AngularJS
Asked Answered
E

3

3

I am trying to restrict input as numbers on below fields

Postal Code:
<input type="text" id="zipCode1" name="zipCode1" size="4" maxlength="5" ng-model="zipCode1" ng-change="myNumbers(zipCode1)" />
<input type="text" id="zipCode2" name="zipCode2" size="3" maxlength="4" ng-model="zipCode2" ng-change="myNumbers(zipCode2)" />

it doesn't work with

$scope.myNumbers = function(fieldName){
var tN = fieldName.replace(/[^\d]/g, "");
    if(tN != fieldName)
    fieldName = tN
};

It works with below code but changing both the fields

$scope.$watch('myNumbers', function() {
var tN = $scope.myNumbers.replace(/[^\d]/g, "");
    if(tN != $scope.myNumbers)
    $scope.myNumbers = tN;
})

Need to change the value for the input field where user is typing and not both

Exam answered 29/1, 2014 at 13:34 Comment(4)
use data-ng-model instead of ng-model .. and it validates automatically. you should not call any function i guessMallina
hi refer mentioned link: #16091718 i think its help to you..Creigh
You should read the angular documentation on form validation. There you will learn how angular validate fields using CSS.Lion
@Edwin Dalorzo 'ng-change' is getting called but the value is not getting assigned using 'fieldName = tN'Exam
R
5

Use the directive found here: https://mcmap.net/q/219482/-angularjs-allows-only-numbers-to-be-typed-into-a-text-box instead of the ng-change function. Replicated here for easy reference:

angular.module('app').
  directive('onlyDigits', function () {

    return {
        restrict: 'A',
        require: '?ngModel',
        link: function (scope, element, attrs, ngModel) {
            if (!ngModel) return;
            ngModel.$parsers.unshift(function (inputValue) {
                var digits = inputValue.split('').filter(function (s) { return (!isNaN(s) && s != ' '); }).join('');
                ngModel.$viewValue = digits;
                ngModel.$render();
                return digits;
            });
        }
    };
});
Risner answered 29/1, 2014 at 13:49 Comment(4)
What's the IE8 behavior? Is it missing something that can be added as a shim?Risner
It is taking characters as well where as in other browsers it is taking only digits, any idea?Exam
Probably related to this behavior difference in split: https://mcmap.net/q/219483/-javascript-split-function-not-working-in-ie - maybe modify the split().join() line into separate statements?Risner
I changed one line of code and it works in all the browsers, var digits = inputValue.split('').filter(function (s) { return (!isNaN(s) && s != ' '); }).join(''); to var digits = inputValue.replace(/[^\d]/g, "");Exam
S
3

You could try adding to the inputs

ng-pattern='/^\d{2}$/'
Sluice answered 29/1, 2014 at 13:37 Comment(2)
Although, that would not prevent you from entering numbers. That would simply mark the field as invalid when the wrong input is given.Lion
@EdwinDalorzo - You're so right! ng-pattern is a bit misleading to beginners.Verbify
A
3

Here is a directive I've done to restrict the keys allowed.

angular.module('app').directive('restrictTo', function() {
    return {
        restrict: 'A',
        link: function (scope, element, attrs) {
            var re = RegExp(attrs.restrictTo);
            var exclude = /Backspace|Enter|Tab|Delete|Del|ArrowUp|Up|ArrowDown|Down|ArrowLeft|Left|ArrowRight|Right/;

            element[0].addEventListener('keydown', function(event) {
                if (!exclude.test(event.key) && !re.test(event.key)) {
                    event.preventDefault();
                }
            });
        }
    }
});

And the input would look like:

<input type="text" name="zipCode1" maxlength="5" ng-model="zipCode1" restrict-to="[0-9]">

The regular expression evaluates the pressed key, not the value.

It also works perfectly with inputs type="number" because prevents from changing its value, so the key is never displayed and it does not mess with the model.

Astigmia answered 17/11, 2016 at 13:34 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.