3
votes

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?

1
You can just use a RegularExpressionAttribute applied to the propertyuser3559349
@StephenMuecke Thanks, that's a very good lead!Csaba Toth
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
That regex would not match what your wanting. I suspect you want the 4th one in Srinivas' answer here?user3559349
@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 worksCsaba Toth

1 Answers

4
votes

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)