FluentValidation。上下文验证器

时间:2015-04-02 12:20:13

标签: asp.net-mvc validation unobtrusive-validation fluentvalidation

假设以下情况:

// [Validator(typeof(AddressForSupplierValidator))] <-- Cannot put both
// [Validator(typeof(AddressForCompanyValidator))]  <--
// But even if I skip both of them it works great for SERVER SIDE
public class Address 
{
     public string AddressName { get; set; }
     public string StreetName { get; set; }
}

[Validator(typeof(SupplierValidator))]
public class Supplier 
{
     public string Name { get; set; }
     public Address Address { get; set; }
}
public class SupplierValidator: AbstractValidator<Supplier> 
{
     public SupplierValidator() {
          RuleFor(x => x.Name).NotEmpty();
          RuleFor(x => x.Address).SetValidator(new AddressForSupplierValidator());

          // AddressForSupplierValidator - Requires AddressName to be .NotEmpty()
     }
}

[Validator(typeof(CompanyValidator))]
public class Company 
{
     public string Name { get; set; }
     public Address Address { get; set; }
}
public class CompanyValidator: AbstractValidator<Company> 
{
     public CompanyValidator() {
          RuleFor(x => x.Name).NotEmpty();
          RuleFor(x => x.Address).SetValidator(new AddressForCompanyValidator());

          // AddressForCompanyValidator - Requires StreetName to be .NotEmpty()
     }
}

如图所示,Address实体正由CompanySupplier使用。

现在我需要根据其上下文验证Address

以上解决方案仅适用于 SERVER SIDE 。但对于 CLIENT SIDE

  

它不会在HTML元素上生成data-val-属性。这是   因为它在顶级[Validator(..)]课程中没有任何Address   定义。添加[Validator(..)]解决了data-val-代   但打破了重用Address实体并验证它的想法   取决于具体情况

问题:

  1. 为什么[Validator()] Address的{​​{1}}突然失效,即使使用.SetValidator(),也会破坏客户端验证?
  2. 为什么我们需要RuleFor(x => x.Address).SetValidator(..);,如果必须在课程顶部指定验证器?
  3. 一些想法:

    1. 我的信念是,为嵌套属性指定.SetValidator(..)就足够了。添加[Validator()]的要求打破了根据上下文重用相同ViewModel和许多验证规则的要求。

    2. 作者已经很好地整合了客户端验证。如果离开重用viewmodel的想法,他们就会工作。

    3. 临时解决方案:

      public class AddressBase
      {
          public string AddressName { get; set;}
          public string StreetName { get; set;}
      }
      
      [Validator(typeof(AddressForSupplierValidator))]
      public class SupplierAddress : AddressBase 
      {}
      
      [Validator(typeof(AddressForCompanyValidator))]
      public class CompanyAddress : AddressBase 
      {}
      

      它有效,但那么.SetValidator(new AddressForSupplierValidator());的原因是什么呢?有点多余。

      参考文献:

      证明这个问题的相关问题发生在:

      Unobtrusive client validation data attributes are not rendered for nested property rules

0 个答案:

没有答案