c# - 流畅验证 : Is it possible to add a RuleSet while invoking a validator using ValidateAndThrow

标签 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 调用验证器时指定规则集

通常这是在调用 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时可以将规则集作为参数传递

我想知道是否也可以使用 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);
        }
    }
}

关于c# - 流畅验证 : Is it possible to add a RuleSet while invoking a validator using ValidateAndThrow,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33556922/

相关文章:

c# - 将对象的一个​​元素传递给 FluentValidation SetValidator 的构造函数

asp.net-mvc - 基于验证对象的自定义属性名称

c# - 关于在 C# 中构建错误代码查找的建议

c# - C#属性类的继承

c# - MVC 两个 Controller 一个 View

asp.net-mvc - ASP.NET MVC - 如何实现分页?

c# - 拖放到托管的浏览器控件

c# - 如何禁用整个系统的空气震动?

c# - 将 asp.net 身份与地理授权一起使用

c# - ServiceStack - FluentValidation