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?

Rookian
  • 19,841
  • 28
  • 110
  • 180

1 Answers1

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; 
       });
   }
}
Alex Art.
  • 8,711
  • 3
  • 29
  • 47
  • Is this going to translate itself into client side (JS) validation also? – RinoTom Jun 07 '18 at 12:05
  • 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: https://stackoverflow.com/questions/9380010/unobtrusive-client-validation-using-fluentvalidation-and-asp-net-mvc-lessthanore – Alex Art. Jun 07 '18 at 12:17