当我需要使用两个验证器验证模型时,我遇到了这种情况:
1)BaseValidator
有一些共同规则的。
2)[Variable]CustomValidator
根据模型的属性之一确定。
将向您展示我大致打算做什么的代码(当然它不起作用,因为没有这样的方法AlsoValidateWith()
)如下:
[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);
}
}
任何帮助表示赞赏!