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 ?
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);
}
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With