2 つのバリデーターを使用してモデルを検証する必要がある場合、次のようなケースがあります。
1)BaseValidator
いくつかの共通ルールがある a。
2)[Variable]CustomValidator
モデルのプロパティの 1 つに基づいて決定されます。
私がおおよそ何をしようとしているのかを示すコード(もちろん、のような方法がないため機能しません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);
}
}
どんな助けでも大歓迎です!