一个模型的两个验证器

时间:2012-07-23 06:33:05

标签: asp.net-mvc fluentvalidation

当我需要使用两个验证器验证模型时,我遇到了这种情况:

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

感谢任何帮助!

1 个答案:

答案 0 :(得分:0)

我不认为使用When方法是可行的,除非您正在验证“子”模型。

但是,调用代码(例如您的控制器)可以调用相应的验证器。这是一个简化的例子:

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.
}

上面的示例使用一个简单的扩展方法来调用流畅的验证:

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;
    }
}
相关问题