I created a custom validator, which tests that an enum is valid, that means it is within the enum's range of valid values:
[DebuggerStepThrough]
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:
[DebuggerStepThrough]
public static IRuleBuilderOptions<T, TProperty> IsInEnum<T, TProperty>(this IRuleBuilder<T, TProperty> ruleBuilder) {
return ruleBuilder.SetValidator(new IsInEnumValidator<TProperty>());
}
To use it:
RuleFor(x => x.Day).IsInEnum<DayOfWeek>();
Now I need to test the validator- not test my data with the validator, but to test the validator itself. The library has quite a bit of stuff going on, so I can't figure out how to do it. Can someone give me a pointer? I use NUnit.