假设以下情况:
// [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
实体正由Company
和Supplier
使用。
现在我需要根据其上下文验证Address
。
以上解决方案仅适用于 SERVER SIDE 。但对于 CLIENT SIDE :
它不会在HTML元素上生成
data-val-
属性。这是 因为它在顶级[Validator(..)]
课程中没有任何Address
定义。添加[Validator(..)]
解决了data-val-
代 但打破了重用Address
实体并验证它的想法 取决于具体情况
[Validator()]
Address
的{{1}}突然失效,即使使用.SetValidator()
,也会破坏客户端验证?RuleFor(x => x.Address).SetValidator(..);
,如果必须在课程顶部指定验证器?我的信念是,为嵌套属性指定.SetValidator(..)
就足够了。添加[Validator()]
的要求打破了根据上下文重用相同ViewModel和许多验证规则的要求。
作者已经很好地整合了客户端验证。如果离开重用viewmodel的想法,他们就会工作。
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