Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Validating enums with a custom FluentValidator validator

I created a custom validator, which tests that a value is within an enum's range of valid values:

public class IsInEnumValidator<T> : PropertyValidator {
  public IsInEnumValidator() : base("Property {PropertyName} it not a valid enum value.") { }
  protected override bool IsValid(PropertyValidatorContext context) {
    if (!typeof(T).IsEnum) return false;
    return Enum.IsDefined(typeof(T), context.PropertyValue);
  }
}

And an extension method for chaining validators:

public static IRuleBuilderOptions<T, TProperty> IsInEnum<T, TProperty>(this IRuleBuilder<T, TProperty> ruleBuilder) {
  return ruleBuilder.SetValidator(new IsInEnumValidator<TProperty>());
}

I want to use use it like this:

RuleFor(x => x.Day).IsInEnum<DayOfWeek>();

My questions:

  1. This doesn't work as expected, as I need to speficy ....IsInEnum<T, DayOfWeek>() instead of the desired ....IsInEnum<DayOfWeek>();. How do I achieve this?

  2. I want to test this custom validator - not to test my data with this validator, but to test the validator itself. The library's docs explain how to test your data, not how to test a custom validator. There seems to be lots of testing code in the library, is there anything I can reuse? I use NUnit.

like image 559
Bobby B Avatar asked Oct 30 '12 22:10

Bobby B


1 Answers

1: Because of type inference, you actually don't need to specify anything in the IsInEnum() call.

2: For testing, the project has lots of tests which can be adapted to fit this scneario.

like image 186
Bobby B Avatar answered Sep 20 '22 23:09

Bobby B