Search code examples
c#fluentvalidation

Fluentvalidation Validator for multiple possible values


Does Fluentvalidation has any built-in function to validate multiple possible option to pass/fail similar to SQL In operator ?

For example : In below code I need to ensure the user_status must be ("Active", "Expired", "Blocked"............) etc.

And for user_role it should be user_role("admin", "manager", "viewer"......)

public class Users
    {

        public string user_status { get; set; }
        public string user_role { get; set; }

    }

    public class UpdateUserValidator : NullReferenceAbstractValidator<Users>
    {
        public UpdateUserValidator()
        {
            RuleFor(user => user.user_status).NotNull();

        }       
    }

Solution

  • As far as I know, there's no built-in validator doing this.

    You could either using a .Must and a collection of accepted values.

    Something like that (of course, the collection of accepted values could be in a variable, and used in the must and message part).

    RuleFor(x =>x.user_status)
    .Must(x => new[]{"Active", "Expired", "Blocked"}.Contains(x))
    .WithMessage("User status should be  either 'active', 'expired' or 'blocked'");
    

    Or you could of course create your own custom validator.