简体   繁体   中英

Validate an object based on a value using FluentValidation

I have a generic object with particular rules setup in my database. I would like to execute particular rules setup in the database, depending on a value within the object.

For example, lets say i have an object like this

public class MyObject {
    public int Type { get; set; }
    public string Name { get; set; }
    public decimal? Value { get; set; }
}

Now if the value of Type is 0, then i need to make sure then Name is populated. If Type is 1, then i need to make sure Name is populated and over 50 chars, and also need Value to be populated.

This is a basic example, and there are more rules as well. So far i have

public class MyObjectValidator : AbstractValidator<MyObject>
{
    public MyObjectValidator()
    {
        // here i would like to check what the value of type is, something like
        if (Type == 1) {
            RuleFor(e => e.Name).NotEmpty().WithMessage("Please enter a name");
        }

        if (Type == 2) {
            RuleFor(....);
        }
    }
}

But i do not know how to get the instance that is being validated.

I really thing it does the job your looking for.

public class MyObjectValidator : AbstractValidator<MyObject>
    {
        public MyObjectValidator()
        {
            RuleFor(x => x.Name).NotEmpty().When(m => m.Type == 1).WithMessage("your msg");
            RuleFor(x => x.Name).Must(s => s.Length > 50).When(m => m.Type == 2).WithMessage("your msg");;
        }
}

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