Michael Rosario
Michael Rosario

Reputation: 848

Using FluentValidation to create validation rule for more than one property

I am trying to implement a complex validation scenario in FluentValidation.

Let's say I have a Car class. It has four properties: Color, Make, Model, Year.

I want to construct a validation rule that involves three of these properties. For the sake of conversation, let's say I want a validation rule like the following:

if car.make = nissan and car.year = 2010 then
    if car.color <> green then
       throw a validation error since the system does not support 2010 nissans that are not green.
    end     
end 

I know this is a silly example. I, however, have validation rules in my app that involve more than one aspect of my object. This is the heart of my question.

I have tried to follow the guidance from http://fluentvalidation.codeplex.com/wikipage?title=Custom on using "Using AbstractValidator.Custom" .

Does anyone have other working examples of the AbstractValidator.Custom working?

Thanks in advance for your time.

Upvotes: 1

Views: 2620

Answers (1)

Suhas
Suhas

Reputation: 8458

Below is a simple way of implementing validations involving multiple properties

public class CarValidator : AbstractValidator<Car>
{
    public CarValidator()
    {
        RuleFor(c => c.Color).NotEqual("Green").When(MakeIsNisssanAndYearIs2000))
    }

    private bool MakeIsNisssanAndYearIs2000(Car arg)
    {
        return arg.Make == "Nissan" && arg.Year == 2000;
    }
}

public class Car
{
    public string Color { get; set; }

    public string Make { get; set; }

    public int Year { get; set; }
}

You can parameterise MakeIsNissanAndYearIs2000 method so that make and model are passed to the method as parameters. But this should give you an idea of how to implement validations involving multiple properties

Upvotes: 2

Related Questions