Question

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

Was it helpful?

Solution

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.

OTHER TIPS

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top