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

4
  • use data-ng-model instead of ng-model .. and it validates automatically. you should not call any function i guess Commented Jan 29, 2014 at 13:36
  • hi refer mentioned link: stackoverflow.com/questions/16091218/… i think its help to you.. Commented Jan 29, 2014 at 13:43
  • You should read the angular documentation on form validation. There you will learn how angular validate fields using CSS. Commented Jan 29, 2014 at 13:45
  • @Edwin Dalorzo 'ng-change' is getting called but the value is not getting assigned using 'fieldName = tN' Commented Jan 29, 2014 at 13:46

3 Answers 3

5

Use the directive found here: https://stackoverflow.com/a/19675023/149060 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;
            });
        }
    };
});
Sign up to request clarification or add additional context in comments.

4 Comments

What's the IE8 behavior? Is it missing something that can be added as a shim?
It is taking characters as well where as in other browsers it is taking only digits, any idea?
Probably related to this behavior difference in split: stackoverflow.com/a/6425425/149060 - maybe modify the split().join() line into separate statements?
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, "");
3

You could try adding to the inputs

ng-pattern='/^\d{2}$/'

2 Comments

Although, that would not prevent you from entering numbers. That would simply mark the field as invalid when the wrong input is given.
@EdwinDalorzo - You're so right! ng-pattern is a bit misleading to beginners.
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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.