FluentValidation:是否可以在使用ValidateAndThrow调用验证器时添加RuleSet

时间:2015-11-05 23:43:20

标签: c# asp.net-mvc fluentvalidation

例如,我有一个Person Validator

public class PersonValidator : AbstractValidator<Person> {

   public PersonValidator() {

      RuleSet("Names", () => {
      RuleFor(x => x.Surname).NotNull();
      RuleFor(x => x.Forename).NotNull();
 });

 RuleFor(x => x.Id).NotEqual(0);
 }
}

如何使用ValidateAndThrow

调用Validator时指定RuleSet

通常这是在调用ValidateAndThrow

时完成的操作
public class ActionClass
{
  private readonly IValidator<Person> _validator;
  public ActionClass(IValidator<Person> validator)
  {
   _validator=validator
  }

  public void ValidateForExample(Person model)
  {
    _validator.ValidateAndThrow(model)

   //When there is no error I can continue with my operations
  }
}

我知道在调用验证

时,可以将Ruleset作为参数传递

我想知道是否可以使用 ValidateAndThrow 来完成?

1 个答案:

答案 0 :(得分:2)

查看source

public static void ValidateAndThrow<T>(this IValidator<T> validator, T instance)
{
    var result = validator.Validate(instance);

    if(! result.IsValid)
    {
        throw new ValidationException(result.Errors);   
    }
}

默认情况下它不允许它,但没有什么可以阻止你创建自己的小扩展方法,它也接受一个规则集名称,如下所示:

public static class ValidationExtensions
{
    public static void ValidateAndThrow<T>(this IValidator<T> validator, T instance, string ruleSet)
    {
        var result = validator.Validate(instance, ruleSet: ruleSet);

        if (!result.IsValid)
        {
            throw new ValidationException(result.Errors);
        }
    }
}