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 since there is not such method as AlsoValidateWith()
) is below:
[Validator(typeof(AnimalValidator))]
public class AnimalModel
{
public string Type { get; set }
public int NumberOfLegs { get; set; }
public string Color { get; set; }
public int NumberOfEyes { get; set; }
public bool HasWings { get; set; }
}
public class AnimalValidator: AbstractValidator<AnimalModel>
{
public AnimalValidator()
{
RuleFor(x => x.NumberOfEyes).Equal(2);
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");
RuleFor(x => x.NumberOfLegs).Equal(2);
RuleFor(x => x.HasWings).Equal(false);
}
}
Any help is appreciated!