[英]angular ng-pattern strange behaviour
example http://plnkr.co/edit/9o9m3VrtaTAxazDhJNqz?p=preview 示例http://plnkr.co/edit/9o9m3VrtaTAxazDhJNqz?p=preview
I want to use pattern in controller for validation in template 我想在控制器中使用模式以在模板中进行验证
angular.module('app', []).controller('ctrl', function ($scope) {
$scope.pat = /(\(|\)|\+|\d)+/g;
})
But ng-pattern validate field when input value is 123-- 但是当输入值为123时ng模式验证字段
<input type="text" ng-pattern="pat" name='asd' ng-model='asd'>
But inline pattern attribute work fine and notice that 123-- is invalid 但是内联模式属性可以正常工作,请注意123--无效
<input type="text" pattern="(\(|\)|\+|\d)+" name='asd' ng-model='asd2'>
What I'm doing wrong? 我做错了什么?
Change your controller to make pat a literal string and not a regex and the behavior will be the same as if you put the pattern directly in the ng-pattern
attribute 更改控制器以使pat成为文本字符串而不是regex,其行为与将模式直接放入
ng-pattern
属性的行为相同
angular.module('app', []).controller('ctrl', function ($scope) {
$scope.pat = '(\\(|\\)|\\+|\\d)+';
});
Change the html to use pat the expression. 更改html以使用pat表达式。
<input type="text" ng-pattern="{{pat}}" name='asd' ng-model='asd'>
Apparently ng-pattern when the value is passed as a string makes it so that the entire string is matched from start to end. 显然,将值作为字符串传递时,ng-pattern使得整个字符串从头到尾都匹配。 So it works as though the regex was wrapped with the
^$
anchors. 因此,它就像用
^$
锚包裹了正则表达式一样工作。
Here is the source from angular.js/validators.js. 这是angular.js / validators.js的源代码。 It shows the regex being converted to aa Regexp if it is a string.
它显示正则表达式(如果它是字符串)将转换为正则表达式。
if (isString(regex) && regex.length > 0) {
regex = new RegExp('^' + regex + '$');
}
So an alternative solution would be to keep your html markup the same and change your controller so that the regular expression matches the entire string by using anchors. 因此,另一种解决方案是保持您的html标记不变,并更改您的控制器,以使正则表达式通过使用锚点匹配整个字符串。 If you put the global flag in the expression, then you get some wonky behavior.
如果将全局标志放在表达式中,则会出现一些奇怪的行为。
angular.module('app', []).controller('ctrl', function ($scope) {
$scope.pat = /^(\(|\)|\+|\d)+$/;
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.