I used Fluent Validator. 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. Even if in BeAValidAddress method is only "return false". 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.

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.

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top