2

Can we negate this expression, if no match found to return true for use in regex attributes (MVC dataannotations)?

Pattern should match:

  1. anything with less than 8 characters OR
  2. anything with no numbers OR
  3. anything with no uppercase OR
  4. anything with no special characters

I want to negate this expression/pattern

[RegularExpression(@"^(.{0,7}|[^0-9]*|[^A-Z]*|[a-zA-Z0-9]*)$")]

I tried ?! with no success:

[RegularExpression(@"^(?!.{0,7}|[^0-9]*|[^A-Z]*|[a-zA-Z0-9]*)$")]

Refering to this answer: Regex password validation, reverse logic

Community
  • 1
  • 1
Legends
  • 21,202
  • 16
  • 97
  • 123

1 Answers1

2

To negate an expression containing several anchored alternatives, you need to group them inside an anchored negative lookahead.

Thus, just add a group (either capturing or non-capturing):

"^(?!(?:.{0,7}|[^0-9]*|[^A-Z]*|[a-zA-Z0-9]*)$).*$"

Since a RegularExpressionAttribute needs a full string match, I added .*$.

Wiktor Stribiżew
  • 607,720
  • 39
  • 448
  • 563