3

I'm using ASP.NET MVC5 which has unobtrusive validator hooked up for the client side validation out of the box. I set up my IdentityConfig.cs this way:

manager.PasswordValidator = new PasswordValidator
{
    RequiredLength = 8,
    RequireNonLetterOrDigit = true,
    RequireDigit = true,
    RequireLowercase = true,
    RequireUppercase = true,
};

When the password is not too long client side validation warns properly. But it doesn't seem to do validation about the rest of the criteria (at least one digit, at least on upper case letter, at least one lower case letter, not even speak about the special characters). In my use-case it'd be important to have these on client side.

What's the best way to enable these extra checks? Should I setup my own non-obtrusive validation rules? How would that interfere with the unobtrusive validation?

Csaba Toth
  • 10,021
  • 5
  • 75
  • 121
  • 1
    You can just use a `RegularExpressionAttribute` applied to the property –  Feb 07 '17 at 05:28
  • @StephenMuecke Thanks, that's a very good lead! – Csaba Toth Feb 07 '17 at 05:42
  • I'm trying `[RegularExpression(@"^(.{0,7}|[^0-9]*|[^A-Z]*|[a-zA-Z0-9]*)$", "Password must have at least...")` but it doesn't seem to trigger. – Csaba Toth Feb 07 '17 at 06:05
  • 1
    That regex would not match what your wanting. I suspect you want the 4th one in [Srinivas' answer here](http://stackoverflow.com/questions/19605150/regex-for-password-must-be-contain-at-least-8-characters-least-1-number-and-bot)? –  Feb 07 '17 at 06:10
  • @StephenMuecke You can add your suggestion as an answer. The reverse logic expression above didn't work, when I'm going with `"^((?=.*\d)(?=.*[A-Z])(?=.*[a-z])(?=.*\W).{8,})$"` the validation triggers and works – Csaba Toth Feb 07 '17 at 06:11
  • @StephenMuecke I'll try that too – Csaba Toth Feb 07 '17 at 18:53

1 Answers1

4

Add a RegularExpressionAttribute to your property. Based on Srinivas' answer to Regex for Password Must be contain at least 8 characters, least 1 number and both lower and uppercase letters and special characters, the following should suit your rules

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

and in the view

@Html.PasswordFor(m => m.Password)
@Html.ValidationMessageFor(m =>m.Password)
Community
  • 1
  • 1