Amandeep Singh
Amandeep Singh

Reputation: 370

Need to a custom Regular expression for model based validation MVC

I am using MVC.net 4 to build a web application. I need to regular expression for password to satisfy following conditions:

  1. Must be between 6-32 characters long.
  2. Must contain at least one lower case letter.
  3. Must contain at least one upper case letter.
  4. Must contain at least one numeric or special character.

Be careful about 4th point, I just need to expression of or condition between numeric and special character(not with and case for number and special character).

i am using following code that is working fine but need to use or case between Numeric and symbols.

[Required(ErrorMessage = "New Password is Required")]
[StringLength(32, MinimumLength = 6, ErrorMessage = "New Password should not be lessthan 6 character.")]
[RegularExpression(@"(?=.*[a-zA-Z0-9])(?=.*[~!@#$%^&*])[a-zA-Z0-9~!@#$%^&*]{8,15}", ErrorMessage = "Password should contain atleast one upper and lower character and on digit or special character.")]
public string NewPassword { get; set; }

i.e. I just need to password Expression as if set amanDeep1 then no need to check for symbol or if set as @amanDeep then no need to check for numeric values.

Upvotes: 0

Views: 423

Answers (1)

Wiktor Stribiżew
Wiktor Stribiżew

Reputation: 626748

You put digits as part of the character class in the first lookahead, and the whole regex is not actually working as you need.

Put the 0-9 to the special chars lookahead requirement, and split the first lookahead to require at least 1 lower AND at least 1 upper case letter:

(?=.*[a-z])(?=.*[A-Z])(?=.*[0-9~!@#$%^&*])[a-zA-Z0-9~!@#$%^&*]+
^^^^^^^^^^^^^^^^^^^^^^      ^^^                               ^          

Note you can just use + at the end, since the length is restricted with the [StringLength(32, MinimumLength = 6, ErrorMessage = "New Password should not be lessthan 6 character.")].

Pattern details:

  • No anchors are used since the pattern inside a RegularExpressionAttribute is anchored by default
  • (?=.*[a-z]) - requires 1 lowercase ASCII letter
  • (?=.*[A-Z]) - requires 1 uppercase ASCII letter
  • (?=.*[0-9~!@#$%^&*]) - requires 1 digit or special char from the set (NOTE that the OR relationship is default between the chars/ranges inside a positive character class)
  • [a-zA-Z0-9~!@#$%^&*]+ - 1 or more chars from the set

Upvotes: 1

Related Questions