简体   繁体   English

流畅的验证规则

[英]Fluent Validation Rule

I used Fluent Validator.我使用了 Fluent 验证器。 I need to create own rule.我需要创建自己的规则。 For example:例如:

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

The problem is that when I use Validate method of AddressValidator class IsValid property is always true.问题是,当我使用 AddressValidator 类的 Validate 方法时,IsValid 属性始终为真。 Even if in BeAValidAddress method is only "return false".即使在 BeAValidAddress 方法中只是“返回假”。 Maybe I forgot something important也许我忘记了一些重要的事情

try must, I always use it 尝试必须,我总是使用它

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

or 要么

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

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

or 要么

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

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

all this mean the same. 这一切意味着相同的。

From documentation of Fluent Validation . 来自Fluent Validation文档。

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

Then you rule never will work because the BeAValidAddress always return false . 然后你的规则永远不会工作,因为BeAValidAddress总是返回false

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

private bool BeAValidAddress(string adress) { private bool BeAValidAddress(字符串地址){

return false;

} }

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

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