0

I trying to validate input with custom directive:

.directive('customValidation', function () {
        return {
            require: 'ngModel',
            link: function (scope, element, attr, ngModelCtrl) {
                function fromUser(text) {
                    element.bind("keydown keypress", function (event) {
                        if (!(event.keyCode >= 48 && event.keyCode <= 57)) {
                            return undefined;
                        }
                    })
                }
                ngModelCtrl.$parsers.push(fromUser);
            }
        };
    });

but it doesn't work. Any character is passes validation. What I doing wrong?

1
  • 1
    Try that plugin plugins.jquery.com/numberMask and uses the link function to join with your field: Ex: $(element).numberMask({beforePoint:2}); Commented Jan 30, 2017 at 16:12

1 Answer 1

1

So basically what you are trying to achieve is to check if an input contains only numbers. At least that is what I can understand from your explanation and the sample code.

First, you are using a parser, which are used for sanitizing and converting values passed from the DOM to the model. Validation comes afterwards. If you just want to check if only numbers are written, then you need something like this:

ngModel.$validators.validCharacters = function(modelValue, viewValue) {
  var value = modelValue || viewValue;
  return /[0-9]+/.test(value);
};

I suggest reading the API docs as they explain all ngModelController functionality very thoroughly: click here for thorough docs

Second, you are binding to a event everytime your parser is called. The parser is called each time you change the contents of your input element. If you type the word everytime into your input, you end up binding the event nine times! Apart from the fact that binding to the event after you changed something is too late as your first event was already fired.

Sign up to request clarification or add additional context in comments.

1 Comment

Probably he needs to disable the entry of other characters than numbers... I used a jquery plugin for that (), and I used the link to join with angular.

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.