Angular reactive forms pattern validator adding $ to regex and breaking validation

前端 未结 1 1762
没有蜡笔的小新
没有蜡笔的小新 2021-01-18 21:54

I\'m trying to validate a password with the following regex:
^(?=.*[A-Z])(?=.*[a-z])(?=.*[0-9])(?=.{8,}).
Note that there is no terminating $

1条回答
  •  清酒与你
    2021-01-18 22:39

    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 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,}$/)
    

    With a regex literal, you may use single backslashes in regex escapes (/\d/ to match a digit vs. "\\d" in a string literal).

    See the regex demo

    Details

    • ^ - 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.

    0 讨论(0)
提交回复
热议问题