Reputation: 2164
I am using an Angular directive to validate a form through a regex. A minimal representation of the code and HTML is given below.
The issue: The weird behavior is the following: the form signals an error with inputs of even length but not with inputs of odd length. Example keystrokes:
a --> valid
aa --> invalid
aaa --> valid
aaaa --> invalid
This happens both when typing and deleting letters. However, if I past aaaa or any string of even length it shows no error. I doubt it might be due to Angular digest loop, but I cannot figure out the issue.
Any clues on what I might want to look at?
Code
This is my directive:
var valid_input_regex = /^[\w]+$/g;
directives.directive('pn', function() {
return {
require: 'ngModel',
link: function(scope, elm, attrs, ctrl) {
ctrl.$validators.pn = function(modelValue, viewValue) {
if (!valid_input_regex.test(modelValue)) {
return false;
}
return true;
};
}
};
});
And in the HTML
<input type="text" class="form-control" name="name" ng-model="name" pn>
<span ng-show="(form.name.$error.pn && !form.name.$pristine)">Please use plain text or numbers.</span>
Upvotes: 0
Views: 121
Reputation: 430
get rid of the 'g' at the end of your regex
var valid_input_regex = /^[\w]+$/;
Should work then
Upvotes: 1