Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

FluentValidation : Is it possible to add a RuleSet while invoking a validator using ValidateAndThrow

For example, I have a Person Validator

public class PersonValidator : AbstractValidator<Person> {

   public PersonValidator() {

      RuleSet("Names", () => {
      RuleFor(x => x.Surname).NotNull();
      RuleFor(x => x.Forename).NotNull();
 });

 RuleFor(x => x.Id).NotEqual(0);
 }
}

How can I specify the RuleSet when invoking the Validator using ValidateAndThrow

Usually this is what is done while calling ValidateAndThrow

public class ActionClass
{
  private readonly IValidator<Person> _validator;
  public ActionClass(IValidator<Person> validator)
  {
   _validator=validator
  }

  public void ValidateForExample(Person model)
  {
    _validator.ValidateAndThrow(model)

   //When there is no error I can continue with my operations
  }
}

I understand that Ruleset can be passed as parameter when caling Validate

I'd like to know if it can be done using ValidateAndThrow as well ?

like image 571
MDJ Avatar asked Oct 30 '22 16:10

MDJ


1 Answers

Looking at the source:

public static void ValidateAndThrow<T>(this IValidator<T> validator, T instance)
{
    var result = validator.Validate(instance);

    if(! result.IsValid)
    {
        throw new ValidationException(result.Errors);   
    }
}

It doesn't allow it by default, but there's nothing stopping you from creating your own little extension method that also takes in a ruleset name, like so:

public static class ValidationExtensions
{
    public static void ValidateAndThrow<T>(this IValidator<T> validator, T instance, string ruleSet)
    {
        var result = validator.Validate(instance, ruleSet: ruleSet);

        if (!result.IsValid)
        {
            throw new ValidationException(result.Errors);
        }
    }
}
like image 139
Yannick Meeus Avatar answered Nov 15 '22 05:11

Yannick Meeus