0

Person class

class person
{
    public string FirstName { get; set; }
    public string FatherName { get; set; }
    public string FamilyName { get; set; }
}

Each property of this class must be validated with this rule

  RuleFor(x => x.FirstName).NotEmpty().Length(2, 50).WithMessage("*");
  RuleFor(x => x.FatherName).NotEmpty().Length(2, 50).WithMessage("*");
  RuleFor(x => x.FamilyName).NotEmpty().Length(2, 50).WithMessage("*"); 

I want to group these properties in one rule that validate each property through these validation rules (NotEmpty, Length)

How to do this in fluent validation ?

wonea
  • 4,783
  • 17
  • 86
  • 139
mohammed sameeh
  • 4,711
  • 3
  • 18
  • 19

2 Answers2

0

If all you care about is just not repeating the steps, you can create array of whatever the lambda/Func/delegate type that fluent validations take, and lip over items in the array calling the same code with only the lambda expression replaced with the one from the array.

Meligy
  • 35,654
  • 11
  • 85
  • 109
0

Perhaps you have already solved your problem, but still. you can create extension class in fluent validation for your field

public class personValidator : AbstractValidator<person>
{
    public MyClassValidator ()
    {
        RuleFor(person => person.FirstName).CheckName();
        RuleFor(person => person.FatherName).CheckName();
        RuleFor(person => person.FamilyName).CheckName();

    }
}

and the check itself

public static IRuleBuilderOptions<T, string>
    CheckName<T>(this IRuleBuilder<T, string> ruleBuilder)
{
    return ruleBuilder.NotEmpty()
                      .Length(2, 50)
                      .WithMessage("*");
}
Aleksey K
  • 13
  • 3