简体   繁体   English

FluentValidation,如何在子验证程序异常消息中包括父属性名称

[英]FluentValidation, how to include parent property name in child validator exception message

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

The exception I'm getting is 我得到的例外是

Exception : Invalid get eligible shipping services request. 例外:无效的获取合格的运输服务请求。 'Email' must not be empty. “电子邮件”不能为空。 Email address is required. 电子邮件地址为必填项。

The message doesn't include that it was actually validation of ShipFromAddress property. 该消息不包括它实际上是对ShipFromAddress属性的验证。

Of course I can pass a reference message to the child validator like "Ship from address", however, maybe there is a more elegant way to do it. 当然,我可以将参考消息传递给子验证程序,例如“从地址寄出货物”,但是,也许有一种更优雅的方法。

Tried something like that, 尝试过这样的事情

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

However the last message was ignored. 但是,最后一条消息被忽略。

Any advise. 任何建议。

Child model should have a reference to parent model, because there are no special means in FlueentValidation for this purpose: 子模型应该引用父模型,因为在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)
    }
}

If you use MVC - just implement ModelBinder, that would set Parent property for child. 如果您使用MVC-仅实现ModelBinder,那将为child设置Parent属性。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM