3

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.

10
  • Are you sure it doesn't work? Seems to be valid, you can verify here regex101.com/r/ZQrWJO/1 Commented Nov 6, 2018 at 16:57
  • 2
    Your regex consists of assertions only. Try it also matching for example .* like ^(?=.*[a-z])(?=.*[A-Z])(?=.*[0-9])(?=.*[^a-zA-Z0-9]).*$ Commented Nov 6, 2018 at 17:06
  • 2
    @Patrick - Javascript and .NET use slightly different regex interpreters. For use with Javascript, test out your expressions with Skinner's tool at regexr.com Commented Nov 6, 2018 at 17:28
  • 2
    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? Commented Nov 6, 2018 at 17:39
  • 1
    @ClayVerValen That has the same effect except that it prevents underscores (and a few other non-English characters). Commented Nov 6, 2018 at 17:44

1 Answer 1

1

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])).*
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.