3
votes

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.

1
Are you sure it doesn't work? Seems to be valid, you can verify here regex101.com/r/ZQrWJO/1Alfredo A.
Your regex consists of assertions only. Try it also matching for example .* like ^(?=.*[a-z])(?=.*[A-Z])(?=.*[0-9])(?=.*[^a-zA-Z0-9]).*$The fourth bird
@Patrick - Javascript and .NET use slightly different regex interpreters. For use with Javascript, test out your expressions with Skinner's tool at regexr.comClay Ver Valen
Side note: The last bit--[^a-zA-Z0-9]--allows anything to be put in as a valid character. This includes the control characters that are at the start of ASCII and anything in the Unicode set that comes above ASCII. Is this what you intended?Kenneth K.
@ClayVerValen That has the same effect except that it prevents underscores (and a few other non-English characters).Kenneth K.

1 Answers

1
votes

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])).*