2
RuleFor(getEligibleShippingDetails => getEligibleShippingDetails.ShipFromAddress)
 .NotNull()
 .WithMessage("Ship from address is required.")
 .SetValidator(shippingFromAddressValidator.FluentValidator)

我得到的例外是

例外:获取合格的运输服务请求无效。“电子邮件”不能为空。电子邮件地址是必需的。

该消息不包括它实际上是对 ShipFromAddress 属性的验证。

当然,我可以将参考消息传递给子验证器,例如“Ship from address”,但是,也许有一种更优雅的方式来做到这一点。

尝试过类似的东西,

RuleFor(getEligibleShippingDetails => getEligibleShippingDetails.ShipFromAddress)
.NotNull()
.WithMessage("Ship from address is required.")
.SetValidator(shippingFromAddressValidator.FluentValidator)
.WithMessage("Invalid ship from address.")

但是最后一条消息被忽略了。

任何建议。

4

1 回答 1

0

子模型应该有对父模型的引用,因为在 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,就会为子级设置 Parent 属性。

于 2015-09-06T09:14:17.590 回答