2

Requirements

I want to check password policies by using multiple regex expressions. For each policy violation I want to display a specific validation message.

Examples:

  • You need to use at least 2 numbers
  • You need to use at least one upper and one lower case letter
  • You need to use at least 8 letters
  • ...

Attempt

I tried to use multiple regex expressions (Fluent Validation Match(string expression)), but ASP.NET MVC does not allow to have multiple regex expressions.

The following validation type was seen more than once: regex

Question

How can I use multiple regex validators in Fluent Validation?

1 Answer 1

3

You can use custom method defined in Abstract validator:

public class UserValidator : AbstractValidator<User> {
   public UserValidator () {
       Custom(user => { 
           Regex r1 = define regex that validates that there are at least 2 numbers
           Regex r2 = define regex for upper and lower case letters
           string message = string.Empty;
           if(!r1.IsMatch(user.password))
           {
               message += "You need to use at least 2 numbers.";
           }
           if(!r2.IsMatch(user.password))
           {
               message += "You need to use at least one upper and one lower case letter.";
           }

           return message != string.Empty;
              ? new ValidationFailure("Password", message )
              : null; 
       });
   }
}
Sign up to request clarification or add additional context in comments.

2 Comments

Is this going to translate itself into client side (JS) validation also?
It is not. If you want client side validation you will have to create a class that generates client side rules. Take a look at this answer: stackoverflow.com/questions/9380010/…

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.