[英]Strange behavior in Angular form validation
I am using an Angular directive to validate a form through a regex.我正在使用 Angular 指令通过正则表达式验证表单。 A minimal representation of the code and HTML is given below.下面给出了代码和 HTML 的最小表示。
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 aa --> 无效
aaa --> valid aaa --> 有效
aaaa --> invalid aaaa --> 无效
This happens both when typing and deleting letters.键入和删除字母时都会发生这种情况。 However, if I past aaaa or any string of even length it shows no error.但是,如果我通过 aaaa 或任何偶数长度的字符串,则不会显示任何错误。 I doubt it might be due to Angular digest loop, but I cannot figure out the issue.我怀疑这可能是由于 Angular 摘要循环造成的,但我无法弄清楚问题所在。
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在 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>
get rid of the 'g' at the end of your regex去掉正则表达式末尾的“g”
var valid_input_regex = /^[\w]+$/;
Should work then那么应该工作
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.