0

In my demo MVC Application I have the following validation rules for validating my domain model classes.

        RuleFor(m => m.Password)
            .Matches(@"^(?=(\d){2,})(?=([a-z])+)(?=(\.\$\~\&)*)").WithMessage("Password should contain at least 2 digits");

But the password validation fails . Basically I want to validate that a password input value should at least contain 2 digits, at least either one of the special characters (.$~&) and at least one alphabet in any order.

They can appear in any order.

Basically I should match the strings like

'a2ss1~A33',
'678.&aA88'

but not

'aaa2sfhdjkf^',
 'aass'.

Also I just came across lookahead s in regex. I still have a doubt why cant just we have the rule for validating the password field ?

.Matches(@"^((\d){2,})(.*[a-zA-Z])([\.\$\~\&]*)").WithMessage("Password should contain at least 2 digits");

When to use lookaheads in regex and when not to ?

1
  • Please post the password the code does not work, what password it should match, which one it shouldn't and just reduce the question to the actual problem. No need to show what works well. Commented Mar 5, 2016 at 21:47

1 Answer 1

4

You can use

^(?=(\D*\d){2})(?=[^A-Za-z]*[A-Za-z])(?=[^.$~&]*[.$~&]).*

See the regex demo.

The regex matches:

  • ^ - start of string
  • (?=(\D*\d){2}) - 2 digits anywhere in the string are required
  • (?=[^A-Za-z]*[A-Za-z]) - an ASCII letter is required somewhere in a string
  • (?=[^.$~&]*[.$~&]) - the symbol from the [.$~&] set is required
  • .* - (optional, remove if full string match is not required) matches all characters other than a newline up to the end of the line

Lookaheads enable several checks from the same position in string (here, at the very beginning as they are all placed right after ^). The regex ^((\d){2,})(.*[a-zA-Z])([\.\$\~\&]*) requires 2 or more digits at the beginning, followed with any 0+ characters other than a newline followed with 1 letter followed with 0+ some special symbols. There can be anything else after that, since you are not checking the end of the string.

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.