简体   繁体   中英

Using element.bind in validation directive

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?

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM