2014-02-06 32 views
10

我正在爲我的請求對象定義驗證。 我希望驗證程序在第一次失敗時停止,而不僅僅是同一個鏈上的那個。 在下面的示例中,如果我的TechnicalHeader對象爲空,當驗證達到TechnicalHeader.MCUserid的規則時,會收到NullReference異常。第一次失敗時停止流暢驗證

在貧困的話,我想在下面的代碼的最後三個規則做了有條件的驗證,根據第一條規則

using System; 
using ServiceStack.FluentValidation; 
using MyProj.Services.Models; 

namespace MyProj.Services.BaseService.Validators 
{ 
    public class BaseValidator<T> : AbstractValidator<T> 
     where T : RequestBase 
    { 
     public BaseValidator() 
     { 
      RuleSet(ServiceStack.ApplyTo.Put | ServiceStack.ApplyTo.Post, 
       () => 
       { 
        this.CascadeMode = CascadeMode.StopOnFirstFailure; 
        RuleFor(x => x.TechnicalHeader).Cascade(CascadeMode.StopOnFirstFailure).NotNull().WithMessage("Header cannot be null"); 
        RuleFor(x => x.TechnicalHeader).NotEmpty().WithMessage("Header cannot be null"); 
        RuleFor(x => x.TechnicalHeader.Userid).NotEmpty().WithMessage("Userid cannot be null or an empty string"); 
        RuleFor(x => x.TechnicalHeader.CabCode).GreaterThan(0).WithMessage("CabCode cannot be or less than 0"); 
        RuleFor(x => x.TechnicalHeader.Ndg).NotEmpty().WithMessage("Ndg cannot be null or an empty string"); 
       } 
      ); 
     } 
    } 
} 

回答

22

的結果運行規則之前就檢查null該取決於他們,使用When條件。

this.CascadeMode = CascadeMode.StopOnFirstFailure; 
RuleFor(x => x.TechnicalHeader).NotNull().WithMessage("Header cannot be null"); 

// Ensure TechnicalHeader is provided 
When(x => x.TechnicalHeader != null,() => { 
    RuleFor(x => x.TechnicalHeader.Userid).NotEmpty().WithMessage("Userid cannot be null or an empty string"); 
    RuleFor(x => x.TechnicalHeader.CabCode).GreaterThan(0).WithMessage("CabCode cannot be or less than 0"); 
    RuleFor(x => x.TechnicalHeader.Ndg).NotEmpty().WithMessage("Ndg cannot be null or an empty string"); 
}); 
+0

謝謝,我猜想,但我認爲有一種方法來告訴驗證器stop.BTW,你知道一些關於http://www.nudoq.org/#!/Packages/FluentValidation-簽名/ FluentValidation/DefaultValidatorOptions/M/OnAnyFailure%28T,TProperty%29?什麼是「OnAnyFailure」用於? – Pizzaboy

+4

@Pizzaboy'CascadeMode.StopOnFirstFailure'只能應用於**當前規則鏈**,而不能應用於後續規則。當您將規則的主題(即RuleFor(x = x.TechnicalHeader))更改爲RuleFor(x = x.TechnicalHeader.UserId)時,您必須啓動一個新鏈。 FluentValidation不能替代檢查null,使用'When'子句覆蓋此檢查。 'OnAnyFailure'不用於ServiceStack的FluentValidation,它也是您鏈接的FluentValidation包的子集。 – Scott

相關問題