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

New Post: Validating enums with a custom FluentValidator validator

$
0
0

So obvious! Anyways I changed the validator so it also works for nullable enums:

    protected override bool IsValid(PropertyValidatorContext context) {
      Type t = typeof(T).IsGenericType
        ? Nullable.GetUnderlyingType(typeof(T))
        : typeof(T);

      // if T is not an enum to begin with, then must fail without checking anything
      if (!t.IsEnum) return false;

      // valid if T is nullable and value is null
      if (typeof(T).IsGenericType && (_context.PropertyValue == null)) return true;

      // valid if it fits within the enum
      return Enum.IsDefined(t, context.PropertyValue);
    }

 

And I got the testing code to work too. Thanks for the pointers.

This is really useful in webforms/mvc enviroment for sanitizing inputs. Please consider adding it to the library the next time you make some mods. Awesome library, thanks!


Viewing all articles
Browse latest Browse all 1917

Trending Articles



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