简体   繁体   中英

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();

        }       
    }

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.

The code snippet in the accepted answer didn't work for me, the working rule what I used was

RuleFor(_ => _.user_status)
.Matches(@"^(Active|Expired|Blocked)")
.WithMessage("User status should be  either 'active', 'expired' or 'blocked'");

FluentValidation 11.2.2

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM