问题描述
我正在尝试使用以下正则表达式验证密码:^(?=.*[A-Z])(?=.*[a-z])(?=.*[0-9])(?=.{8,})
.
请注意,没有终止 $
字符,因为这会阻止接受有效密码.(我不确定为什么输入字段不终止字符串).
然而,Angular 的 Validators.pattern
添加了字符串字符的结尾.因此我的有效密码失败.
如何防止模式验证器添加 $
?
我想我可以推出自己的密码验证器,但肯定有更好的解决方案......?
I'm trying to validate a password with the following regex:^(?=.*[A-Z])(?=.*[a-z])(?=.*[0-9])(?=.{8,})
.
Note that there is no terminating $
char, because that would prevent valid passwords from being accepted. (I'm not sure why the input field doesn't terminate the string).
However, Angular's Validators.pattern
adds the end of string char. And therefore my valid passwords fail.
How do I prevent the pattern validator from adding the $
?
I suppose I could roll my own password validator, but surely there is a better solution...?
应该成功的密码:
- Test1234
- tEst1234
- test1234
- 1234测试
- 1234 次测试
- t#St1234
应该失败的密码:
- TEST1234
- test1234
- tEst123
- 测试123
- 测试
- 12345678
验证器声明:
this.password = new FormControl('', [Validators.required, Validators.pattern('^(?=.*[A-Z])(?=.*[a-z])(?=.*[0-9])(?=.{8,})')]);
this.userForm.addControl('Password', this.password);
推荐答案
你可以在最后添加一个 .*
,或者甚至稍微修改一下模式,将一个前瞻模式转换为一个消费模式:
You may add a .*
at the end, or even revamp the pattern a bit to convert one lookahead into a consuming pattern:
Validators.pattern('(?=.*[A-Z])(?=.*[a-z])(?=.*[0-9]).{8,}')
或者,更好的是,在使用正则表达式进行密码验证时,遵循对比原则:
Or, better, when using a regex for password validation, follow the principle of contrast:
Validators.pattern('(?=[^A-Z]*[A-Z])(?=[^a-z]*[a-z])(?=[^0-9]*[0-9]).{8,}')
Angular 会在正则表达式模式的两端添加 ^
和 $
,所以模式看起来像
Angular will add ^
and $
on both ends of the regex pattern, so the pattern will look like
^(?=[^A-Z]*[A-Z])(?=[^a-z]*[a-z])(?=[^0-9]*[0-9]).{8,}$
请注意,如果您使用正则表达式,它不会自动添加锚点,请手动添加:
Note it won't add the anchors automatically if you use a regex literal, add them manually:
Validators.pattern(/^(?=[^A-Z]*[A-Z])(?=[^a-z]*[a-z])(?=\D*\d).{8,}$/)
使用正则表达式文字,您可以在正则表达式转义中使用单个反斜杠(/\d/
匹配数字与字符串文字中的 "\\d"
).
With a regex literal, you may use single backslashes in regex escapes (/\d/
to match a digit vs. "\\d"
in a string literal).
查看正则表达式演示
详情
^
- 字符串的开始(?=[^A-Z]*[A-Z])
- 至少 1 个大写 ASCII 字母(?=[^a-z]*[a-z])
- 至少 1 个小写 ASCII 字母(?=[^0-9]*[0-9])
- 至少 1 个 ASCII 数字.{8,}
- 任何 8 个或更多字符(换行符除外)$
- 字符串结束.
^
- start of string(?=[^A-Z]*[A-Z])
- at least 1 uppercase ASCII letter(?=[^a-z]*[a-z])
- at least 1 lowercase ASCII letter(?=[^0-9]*[0-9])
- at least 1 ASCII digit.{8,}
- any 8 or more chars (other than line break chars)$
- end of string.
这篇关于Angular 反应形式模式验证器将 $ 添加到正则表达式并破坏验证的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!