Quantcast
Channel: Fluent Validation for .NET
Viewing all articles
Browse latest Browse all 1917

New Post: How to create validator for type?

$
0
0
I mean, you can put the logic for checking the type in a Must call which is wrapped in an extension method. This is just as reusable, but doesn't require a custom validator.
public static class MyExtensions {
    public static IRuleBuilderOptions<T, string> CanConvert<T>(this IRuleBuilder<T, string> ruleBuilder, Type type) {
        return ruleBuilder.Must(value => {
            var descriptor = TypeDescriptor.GetConverter(type);
            if(descriptor == null) return false;
            return descriptor.IsValid(value);
        });
    }
}
Useable like this:
RuleFor(x => x.Forename).CanConvert(typeof(int));

Viewing all articles
Browse latest Browse all 1917

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>