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:
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?
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.
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.
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