2015-06-11 48 views
2

我有下面的代碼來驗證實體:檢查其他規則與fluentvalidation

public class AffiliateValidator : AbstractValidator<Affiliate> 
    { 
    public AffiliateValidator() 
    { 
     RuleFor(x => x.IBAN).SetValidator(new ValidIBAN()).Unless(x => String.IsNullOrWhiteSpace(x.IBAN)); 
    } 
    } 

而且ValidIBAN()代碼:

public class ValidIBAN : PropertyValidator 
{ 
    public ValidIBAN() 
     :base("IBAN \"{PropertyValue}\" not valid.") 
    { 

    } 

    protected override bool IsValid(PropertyValidatorContext context) 
    { 
     var iban = context.PropertyValue as string; 
     IBAN.IBANResult result = IBAN.CheckIban(iban, false); 
     return result.Validation == (IBAN.ValidationResult.IsValid); 
    } 

} 

}

所以,IBAN類的CheckIBAN方法做骯髒的工作。

現在,我需要對另一個屬性應用以下規則: 如果DirectDebit(bool)爲true,那麼IBAN不能爲空,也必須有效。

我可以這樣做:

RuleFor(x => x.DirectDebit).Equal(false).When(a => string.IsNullOrEmpty(a.IBAN)).WithMessage("TheMessage."); 

但我怎麼能調用另一個規則,IBAN在這種情況下規則,以檢查是否是或者不是有效?

+0

我編輯了你的標題。請參閱:「[應該在其標題中包含」標籤「](http://meta.stackexchange.com/questions/19190/)」,其中的共識是「不,他們不應該」。 –

+0

@JohnSaunders:對不起。我不確定發佈的標題是什麼。但下次會記住。 – Txaran

+0

「C#fluentvalidation檢查另一個規則」 –

回答

0

通常這些問題比看起來簡單。這是我採用的解決DirectDebit字段規則的解決方案。

RuleFor(x => x.DirectDebit).Must(HaveValidAccounts).When(x => x.DirectDebit) 
      .WithMessage("TheMessage"); 

和改變也爲IBAN規則:

RuleFor(x => x.IBAN).Must(IsValidIBAN) 
          .Unless(x => String.IsNullOrWhiteSpace(x.IBAN)) 
          .WithMessage("The IBAN \"{PropertyValue}\" is not valid."); 

...然後:

private bool HaveValidAccounts(ViewModel instance, bool DirectDebit) 
    { 
     if (!DirectDebit) 
     { return true; } 

     bool CCCResult = IsValidCCC(instance.CCC); 
     bool IBANResult = IsValidIBAN(instance.IBAN); 

     return CCCResult || IBANResult; 
    } 

    private bool IsValidIBAN(string iban) 
    { 
     return CommonInfrastructure.Finantial.IBAN.CheckIban(iban, false).Validation == IBAN.ValidationResult.IsValid; 
    } 

訣竅是使用必須()的實例參數做whetever我想。

相關問題