嗨,我有类似的类结构
public class Order
{
public Address OfficeAddress {get;set;}
}
public class Address
{
public string ID {get;set;}
public string Street1 {get;set;}
public string street2 {get;set;}
public string City {get;set;}
public string State {get;set;}
public string ZipCode {get;set;}
}
我有订单的验证器,如下
public OrderValidator : AbstractValidator<Order>
{
public OrderValidator()
{
Custom(Order =>
{
//Did some custom validation...works fine.
});
RuleFor(o => o.OfficeAddress.StreetLine1)
.Cascade(CascadeMode.StopOnFirstFailure)
.NotEmpty().WithLocalizedMessage(() => Myresource.required)
.Length(1, 60).WithLocalizedMessage(() => Myresource.maxLength)
.Unless(o => null == o.OfficeAddress);
}
}
我的消息显示为这样的
Office Address. Street Line1 is required
为什么要附加"办公地址"?为什么要拆分属性名称?我的资源消息是这样的{PropertyName}是必需的。现在,我该如何告诉它不要显示"办公室地址",也不要拆分它。
我在其他视图中也有类似的复杂地址属性,但它在那里运行良好,我不知道为什么。唯一的区别是,所有其他验证器都定义了RuleSet,在它们内部,我类似地验证地址,但在上面,它不在RuleSet中。在这里,对于控制器中的视图Post Action方法,甚至我没有提到[CustomizeValidator(RuleSet = "RuleSetName")]
,因为我在上面进行了自定义验证。不确定这是否是问题所在。
即使我决定使用RuleSet,我是否可以在同一个Validator中拥有"RuleSet"和自定义Validator?如果是,那么我应该如何将RuleSet命名为"地址"?并用相同的名称标记Action M方法,它将调用Custom和"Address"规则集?
您应该为Address
类定义一个单独的验证器:
public class AddressValidator: AbstractValidator<Address>
{
public void AddressValidator()
{
this
.RuleFor(o => o.StreetLine1)
.Cascade(CascadeMode.StopOnFirstFailure)
.NotEmpty().WithLocalizedMessage(() => Myresource.required)
.Length(1, 60).WithLocalizedMessage(() => Myresource.maxLength)
.Unless(o => null == o);
}
}
然后在您的订单验证器中:
public OrderValidator : AbstractValidator<Order>
{
public OrderValidator()
{
Custom(Order =>
{
//Did some custom validation...works fine.
});
this
.RuleFor(o => o.OfficeAddress)
.SetValidator(new AddressValidator());
}
}