RuleFor(getEligibleShippingDetails => getEligibleShippingDetails.ShipFromAddress)
.NotNull()
.WithMessage("Ship from address is required.")
.SetValidator(shippingFromAddressValidator.FluentValidator)
得到的例外是
Exception: Invalid get eligible shipping services request。"Email"不能是空的。邮件地址是必需的
消息不包括它实际上是验证ShipFromAddress属性。
当然,我可以传递一个引用消息给子验证器,比如"从地址发送",但是,也许有一种更优雅的方法。
试过了,
RuleFor(getEligibleShippingDetails => getEligibleShippingDetails.ShipFromAddress)
.NotNull()
.WithMessage("Ship from address is required.")
.SetValidator(shippingFromAddressValidator.FluentValidator)
.WithMessage("Invalid ship from address.")
但是最后一条消息被忽略了。
任何建议。子模型应该有对父模型的引用,因为在FlueentValidation中没有特殊的方法:
public class Parent
{
public int Id {get;set;}
public Child ChildModel {get;set;}
}
public class Child
{
public string Name {get;set;}
public Parent ParentModel {get;set;}
}
public class ChildValidator : AbstractValidator<Child>
{
public ChildValidator()
{
RuleFor(x => x.Name)
.NotNull()
.WithMessage("Name should not be null for child of {0}'s parent", (model, value) => model.Parent.Id)
}
}
如果你使用MVC -只实现ModelBinder,那将为child设置Parent属性。