0

I'm trying to create a validation rule whereby I can pass in two parameters into a method called by Must()

My models;

public class Make
{
    public int MakeId { get; set; }
    public string Name { get; set; }
    public Car[] Cars { get; set; }
}

public class Car
{
    public int CarId { get; set; }
    public string Name { get; set; }
}

Validator

public class MakeValidator : AbstractValidator<Make>
{
    public MakeValidator()
    {
        When(car => car.Cars != null && car.Cars.Any(), () =>
        {               
            RuleFor(car => car.Car)
                .Must(car => ValidateCar(car.CarId, MakeId)
                .WithMessage("Invalid Car");
        });
    }

    public bool ValidateCar(Car[] Cars, int makeId)
    {
        foreach (var car in Cars)
        {
            // *** internal logic ***
        }
        return true;
    }
}
wonea
  • 4,783
  • 17
  • 86
  • 139

1 Answers1

1

use

Must((y, x) => 

instead of

Must(x =>

where y represents your class, and x your property

so to make things clearer

.Must((car, make) => ValidateCarMake(make, car.CarId)

EDIT

from the signature of your ValidateCarMake method, it should be

either

RuleFor(car => car.Makes)
     .Must((car, make) => ValidateCarMake(make, car.CarId)
     .WithMessage("Invalid Car Make");

or

RuleFor(car => car.Make)
      .Must((car, make) => ValidateCarMake(car.Makes, car.CarId)
      .WithMessage("Invalid Car Make");
Raphaël Althaus
  • 59,727
  • 6
  • 96
  • 122
  • Thanks for answering my confusing question with a clear answer. Very much appreciated. Great insight. – wonea Jul 11 '14 at 14:13