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 was trying a custom validator:
  public class TypeValidator<T> : PropertyValidator {

    public TypeValidator()
      : base("The type is not valid") {
    }

    protected override Boolean IsValid(PropertyValidatorContext context) {
      String value = (String)context.PropertyValue;
      TypeConverter converter = TypeDescriptor.GetConverter(typeof(T));
      return converter != null ? converter.IsValid(value) : false;
    }
  }
And the extension:
    public static IRuleBuilderOptions<T, String> Type<T>(this IRuleBuilder<T, String> builder) {
      return builder.SetValidator(new TypeValidator<T>());
    }
But somehow I am able to do this:
RuleFor(x => x.Position).Type<Int16>();
But not this:
RuleFor(x => x.Position).Type<Int16>().WithMessage("Value is invalid");
What am I missing? And do you think this will work?

Thank You,
Miguel

Viewing all articles
Browse latest Browse all 1917

Trending Articles



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