0

您好我有階級結構這樣流利的驗證複雜屬性的消息顯示覆雜屬性名稱在它

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")],因爲我有上面的自定義驗證。不知道這是否是問題。

即使我決定使用RuleSet,那麼我是否可以在同一個Validator中使用「RuleSet」以及Custom Validator?如果是,那麼我應該如何將RuleSet命名爲「Address」?並用相同的名稱標記Action MEthod,它將調用Custom以及「Address」RuleSet?

回答

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()); 
    } 
} 
+0

它的工作就像一個魅力...感謝的人..... – user2232861