加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

正则表达式 – Angular ng-pattern不检查正则表达式的上限字符

发布时间:2020-12-14 05:50:31 所属栏目:百科 来源:网络整理
导读:我刚刚开始测试ng-pattern与我在非Angular项目中使用的一些正则表达式并且工作正常.但是使用ng-pattern它们似乎不起作用.例如,我有这个正则表达式,成功检查一个包含至少1个字母和1个数字字符的6-20个字符的字符串: "^.*(?=.{6,20})(?=.*d)(?=.*[a-zA-Z]).*
我刚刚开始测试ng-pattern与我在非Angular项目中使用的一些正则表达式并且工作正常.但是使用ng-pattern它们似乎不起作用.例如,我有这个正则表达式,成功检查一个包含至少1个字母和1个数字字符的6-20个字符的字符串:

"^.*(?=.{6,20})(?=.*d)(?=.*[a-zA-Z]).*$"

但是,在我下面的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>

我在语法中是否有一些错误,或者是否有其他原因导致无效?

解决方法

你错过了一个结束锚,你有一个.*太多了(在开始时):

^             # 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

这可行:

"^(?=.{6,20}$)(?=.*d)(?=.*[a-zA-Z]).*$"

但是,在前瞻之外进行长度检查会更容易(也更明显):

"^(?=.*d)(?=.*[a-zA-Z]).{6,20}$"

(这反过来让我问你为什么要施加这么低的上限?我的KeePass生成的密码长度通常至少为30个字符,例如)

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读