【问题标题】:FluentValidation, how to include parent property name in child validator exception messageFluentValidation,如何在子验证器异常消息中包含父属性名称
【发布时间】:2015-09-02 11:25:16
【问题描述】:
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.")

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

任何建议。

【问题讨论】:

    标签: c# fluentvalidation fluentvalidation-2.0


    【解决方案1】:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-01-08
      相关资源
      最近更新 更多