流利的验证规则

时间:2014-04-08 21:13:32

标签: c# fluentvalidation

我使用了Fluent Validator。我需要创建自己的规则。例如:

public class Address
{
    public string Street { get; set; }
}

public class AddressValidator:AbstractValidator<Address>
{
    public AddressValidator()
    {
        RuleFor(a => a.Street).NotEmpty().When(a => BeAValidAddress(a.Street));
    }

    private bool BeAValidAddress(string adress)
    {
        //...some logic
        return false;
    }
}

问题是,当我使用AddressValidator类的Validate方法时,IsValid属性始终为true。即使在BeAValidAddress方法中只是“返回false”。也许我忘记了重要的事情

2 个答案:

答案 0 :(得分:2)

尝试必须,我总是使用它

RuleFor(a => a.Street).Must(x => x=="hello"); 
//will return false untill a.street == hello

RuleFor(a => a.Street).Must(BeAValidAddress())

private bool BeAValidAddress(string adress)
{
    //...some logic
    return false;
}

RuleFor(a => a.Street).Must(x => BeAValidAddress(x))

private bool BeAValidAddress(string adress)
{
    //...some logic
    return false;
}

这一切意味着相同。

答案 1 :(得分:1)

来自Fluent Validation的文档。

The When and Unless methods can be used to specify conditions that control
when the rule should execute. 

然后你的规则永远不会起作用,因为BeAValidAddress总是返回false