Miguel Moura
Miguel Moura

Reputation: 39484

Validate password with Regex

I need to check if a password has at least:

I have the following in C#:

@"^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)(?=.*[$@$!%*?&])[A-Za-z\d$@$!%*?&]"

But this is not validating:

"Ab!123"

What am I missing?

UPDATE

I am using this with System.ComponentModel.DataAnnotations to validate a model property:

  [RegularExpression(@"^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)(?=.*[$@$!%*?&])[A-Za-z\d$@$!%*?&]"]    
  public String Password { get; set; }

Upvotes: 0

Views: 76

Answers (1)

Jan
Jan

Reputation: 43189

Plain simple: you do not have a quantifier. Use

@"^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)(?=.*[$@$!%*?&])[A-Za-z\d$@$!%*?&]+"

instead (see the + at the end of the expression?) See a working demo on regex101.com.
In contrast to the comments, the dot does not need to be escaped in square brackets ([]). Additionally, you can still optimize your expression:

@"^(?=[^a-z]*[a-z])(?=[^A-Z]*[A-Z])(?=\D*\d)(?=.*[$@$!%*?&])[A-Za-z\d$@$!%*?&]+"

Upvotes: 2

Related Questions