Search code examples
c#fluentvalidation

Fluent Validation Rule


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


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.