【问题标题】:Fluent Validation Complex Property message shows Complex Property Name in itFluent Validation Complex Property 消息在其中显示复杂属性名称
【发布时间】:2013-06-21 13:38:29
【问题描述】:

嗨,我有这样的类结构

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 中。即使我没有提到[CustomizeValidator(RuleSet = "RuleSetName")],因为我在上面进行了自定义验证,所以这里对于这个 View in controller Post Action 方法。不知道是不是这个问题。

即使我决定使用 RuleSet,我是否可以在同一个验证器中拥有“RuleSet”以及自定义验证器?如果是,那么我应该将 RuleSet 命名为“地址”吗?并用相同的名称标记动作方法,它将同时调用自定义和“地址”规则集?

【问题讨论】:

    标签: validation asp.net-mvc-4 server-side fluent fluentvalidation


    【解决方案1】:

    您应该为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);
        }
    }
    

    然后在您的 OrderValidator 中:

    public OrderValidator : AbstractValidator<Order>
    {
        public OrderValidator()
        {
            Custom(Order =>
            {
                //Did some custom validation...works fine.
            });
    
            this
                .RuleFor(o => o.OfficeAddress)
                .SetValidator(new AddressValidator());
        }
    }
    

    【讨论】:

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