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

例如,我有一个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
  }
}

我知道在调用Validate时可以将Ruleset作为参数传递

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

最佳答案 看看
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);
        }
    }
}
点赞