Search code examples
c#regexasp.net-mvcunobtrusive-validation

Valid RegEx doesn't work with ASP.Net MVC RegularExpression attribute


I have a regular expression to validate password rules.

In a .Net Console application, it is correctly rejecting or validating passwords as expected.

var strongRegex = new Regex("^(?=.*[a-z])(?=.*[A-Z])(?=.*[0-9])(?=.*[^a-zA-Z0-9])");
Console.WriteLine(strongRegex.IsMatch("Test_1234"));

This returns "true", as expected.

When I add this to my model in an ASP.Net MVC project, this same value is being rejected by jQuery's unobtrusive validation on the client.

[RegularExpression("^(?=.*[a-z])(?=.*[A-Z])(?=.*[0-9])(?=.*[^a-zA-Z0-9])"]

I viewed the page source to see how this is being rendered due to reading about case-sensitivity issues in prior framework versions, but that doesn't seem to be the case here ... it renders the following on the input element:

data-val-regex-pattern="^(?=.*[a-z])(?=.*[A-Z])(?=.*[0-9])(?=.*[^a-zA-Z0-9])"

And this causes the same value that works in the console application ("Test_1234") to fail client-side validation.


Solution

  • Seems like your password validation rules are:

    1. Must have at least 1 digit
    2. Must have at least 1 upper case character
    3. Must have at least 1 lower case character
    4. Must have at least 1 other character that doesn't match one of the first three rules.

    If I am reading this right, try this:

    ^((?=.*\d)(?=.*[a-z])(?=.*[A-Z])(?=.*[^a-zA-Z0-9])).*