Quantcast
Channel: Fluent Validation for .NET
Viewing all articles
Browse latest Browse all 1917

New Post: Two Validators for one Model

$
0
0

Hello Jeremy,

I have this case when I need to validate a model with two validators:

1) a BaseValidator that has some common rules.

2) [Variable]CustomValidator which is determined based on one of the Model's properties.

Code that will show you what I approximately intend to do (of course it does not work) is below:

 

[Validator(typeof(AnimalValidator))]
public class AnimalModel
{
    public string Type { get; set }
    public int NumberOfLegs { get; set; }
    public string Color { get; set; }
}

public class AnimalValidator: AbstractValidator<AnimalModel>
{
    public AnimalValidator()
    {
        RuleFor(x => x.NumberOfLegs).Equal(4).When(x => x.Type == "Dog");
        RuleFor(x => x).AlsoValidateWith(new DogValidator()).When(x => x.Type == "Dog");
        RuleFor(x => x).AlsoValidateWith(new CatValidator()).When(x => x.Type == "Cat");
    }
}

public class DogValidator: AbstractValidator<AnimalModel>
{
    public DogValidator()
    {
        RuleFor(x => x.Color).Equal("Black")
    }
}

Any help is appreciated!


Viewing all articles
Browse latest Browse all 1917

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>