我刚刚开始测试ng-pattern与我在非Angular项目中使用的一些正则表达式并且工作正常.但是使用ng-pattern它们似乎不起作用.例如,我有这个正则表达式,成功检查一个包含至少1个字母和1个数字字符的6-20个字符的字符串:
"^.*(?=.{6,20})(?=.*\d)(?=.*[a-zA-Z]).*$"
Run Code Online (Sandbox Code Playgroud)
但是,在我的Angular示例中,它会成功检查所有内容,但是当字符串超过20个字符时不会触发它:
<div class="controls">
<input type="text" ng-model="user.Password" id="Password" name="Password" title="Password" required ng-pattern="^/.*(?=.{6,20})(?=.*\d)(?=.*[a-zA-Z]).*$/" />
<span ng-show="form.Password.$dirty && form.Password.$error.required">{{'_PasswordRequired_' | i18n}}</span>
<span ng-show="form.Password.$dirty && form.Password.$error.pattern">{{'_PasswordLengthAndAlphanumeric_' | i18n}}</span>
</div>
Run Code Online (Sandbox Code Playgroud)
我在语法中是否有一些错误,或者是否有其他原因导致无效?
你错过了一个结束锚,你有一个 .*太多(在开始时):
^ # Start of string
.* # Match *any* number of characters
(?=.{6,20}) # *Then* check that 6-20 characters follow
<snip>
.* # *Then* match any number of characters anyway
$ # until the end of the string
Run Code Online (Sandbox Code Playgroud)
这可行:
"^(?=.{6,20}$)(?=.*\d)(?=.*[a-zA-Z]).*$"
Run Code Online (Sandbox Code Playgroud)
但是,无论如何,在前瞻之外进行长度检查会更容易(也更明显):
"^(?=.*\d)(?=.*[a-zA-Z]).{6,20}$"
Run Code Online (Sandbox Code Playgroud)
(这反过来让我问你为什么要施加这么低的上限?我的KeePass生成的密码长度通常至少为30个字符,例如)