0

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);
    }
}

どんな助けでも大歓迎です!

4

1 に答える 1

0

I don't think this is possible using the When method unless you're validating a "child" model.

However, the calling code (e.g. your controller) could instead invoke the appropriate validator. Here's a simplified example:

public ActionResult SomeAction(AnimalModel model)
{    
    ModelState.Clear();

    if (model.Type == "Dog")
        model.ValidateModel(new DogFullValidator(), ModelState);
    else if (model.Type == "Cat")
        model.ValidateModel(new CatFullValidator(), ModelState);

    // etc.
}

The above example uses a simple extension method to call the fluent validation:

public static class ValidationExtensions
{
    public static ModelStateDictionary ValidateModel<TModel, TValidator>(this TModel model, TValidator validator, ModelStateDictionary modelState)
        where TModel : class
        where TValidator : AbstractValidator<TModel>
    {
        var result = validator.Validate(model);

        result.AddToModelState(modelState, string.Empty);

        return modelState;
    }
}
于 2012-12-20T11:06:05.200 に答える