角反应形式模式验证器在正则表达式中添加$并破坏验证 [英] Angular reactive forms pattern validator adding $ to regex and breaking validation

查看:86
本文介绍了角反应形式模式验证器在正则表达式中添加$并破坏验证的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用以下正则表达式验证密码:
^(?=.*[A-Z])(?=.*[a-z])(?=.*[0-9])(?=.{8,}).
请注意,没有终结符$ char,因为这将阻止接受有效的密码. (我不确定为什么输入字段不终止字符串).
但是,Angular的Validators.pattern添加了字符串char的末尾.因此,我的有效密码失败.
如何防止模式验证器添加$?
我想我可以使用自己的密码验证器,但是肯定有更好的解决方案...?

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
  • 1234Test
  • 1234tesT
  • t#St1234

应该失败的密码:

  • TEST1234
  • test1234
  • tEst123
  • Test123
  • testtest
  • 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,}$

请注意,如果您使用 regex文字,它将不会自动添加锚点,请手动添加它们:

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).

请参见 regex演示

详细信息

  • ^-字符串开头
  • (?=[^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.

这篇关于角反应形式模式验证器在正则表达式中添加$并破坏验证的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆