FluentValidation: is it possible to add a RuleSet when calling a validator using ValidateAndThrow

For example, I have an identity checker

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 tell RuleSet when calling Validator using ValidateAndThrow

This is usually what is done when 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 a Ruleset can be passed as a parameter when calibrating Validate

I would like to know if this can be done using ValidateAndThrow ?

+4
source share
1 answer

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);   
    }
}

, , , :

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);
        }
    }
}
+2

Source: https://habr.com/ru/post/1614666/


All Articles