简体   繁体   English

使用 fluentvalidation 检查另一个规则

[英]check another rule with fluentvalidation

I have the following code to validate an entity:我有以下代码来验证实体:

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

And ValidIBAN() Code:和 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);
    }

}

} }

So,CheckIBAN method of IBAN class does the dirty job.因此,IBAN 类的 CheckIBAN 方法完成了肮脏的工作。

Now, what I need to to is apply the following rule for another property: If DirectDebit (bool) is true, then IBAN can't be empty and also it must be valid.现在,我需要对另一个属性应用以下规则:如果 DirectDebit (bool) 为真,则 IBAN 不能为空,并且必须有效。

I can do this:我可以做这个:

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

But how can I Invoke another rule, IBAN's rule in this case, in order to check if is or not valid?但是我如何调用另一个规则,在这种情况下是 IBAN 的规则,以检查是否有效?

Often the problems are simpler than they seem.问题往往比看起来更简单。 This is the solution I adopt to aply the rule for DirectDebit field.这是我为 DirectDebit 字段应用规则所采用的解决方案。

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

and change the rule for IBAN also:并更改 IBAN 的规则:

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

...and then: ...进而:

   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;
    }

the trick is use instance parameter of Must() to do whetever I want.诀窍是使用 Must() 的实例参数来做我想做的任何事情。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM