0

I have a generic object with particular rules setup in my database. I would like to execute particular rules setup in the database, depending on a value within the object.

For example, lets say i have an object like this

public class MyObject {
    public int Type { get; set; }
    public string Name { get; set; }
    public decimal? Value { get; set; }
}

Now if the value of Type is 0, then i need to make sure then Name is populated. If Type is 1, then i need to make sure Name is populated and over 50 chars, and also need Value to be populated.

This is a basic example, and there are more rules as well. So far i have

public class MyObjectValidator : AbstractValidator<MyObject>
{
    public MyObjectValidator()
    {
        // here i would like to check what the value of type is, something like
        if (Type == 1) {
            RuleFor(e => e.Name).NotEmpty().WithMessage("Please enter a name");
        }

        if (Type == 2) {
            RuleFor(....);
        }
    }
}

But i do not know how to get the instance that is being validated.

brduca
  • 3,573
  • 2
  • 22
  • 30
Gillardo
  • 9,518
  • 18
  • 73
  • 141

1 Answers1

0

I really thing it does the job your looking for.

public class MyObjectValidator : AbstractValidator<MyObject>
    {
        public MyObjectValidator()
        {
            RuleFor(x => x.Name).NotEmpty().When(m => m.Type == 1).WithMessage("your msg");
            RuleFor(x => x.Name).Must(s => s.Length > 50).When(m => m.Type == 2).WithMessage("your msg");;
        }
}
brduca
  • 3,573
  • 2
  • 22
  • 30
  • I have to check the Type property before validation loads of other properties (say 50) and dont really want to have to type When(m => m.Type == ?) every time (unless i have too). Is there a way of doing this before RuleFor so i can do 1 if statement and check 50 properties, rather than putting this if on each property? – Gillardo Dec 01 '14 at 16:11
  • RuleFor(x => x) .Must(o => { if (o.Type == 1) { if (o.Name.Length < 50) return false; } return true; }).WithMessage("My fail message 1") .Must(p => { if (p.Type == 2) { // Keep validating } return true; }).WithMessage("My fail message 2"); – brduca Dec 01 '14 at 16:45