Created
November 16, 2013 06:53
-
-
Save danielmackay/7496827 to your computer and use it in GitHub Desktop.
Web Api enumeration validation attribute. #webapi, #enum
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System; | |
using System.ComponentModel.DataAnnotations; | |
using System.Globalization; | |
namespace Asset.Web.Filters | |
{ | |
/// <summary> | |
/// Checks if an enumeration is valid. Will return true if no value is specified. | |
/// </summary> | |
public class EnumAttribute: ValidationAttribute | |
{ | |
public Type Type { get; set; } | |
private const string DefaultErrorMessage = "'{0}' is not valid."; | |
public EnumAttribute(Type type) | |
: base(DefaultErrorMessage) | |
{ | |
Type = type; | |
} | |
public override string FormatErrorMessage(string name) | |
{ | |
return String.Format(CultureInfo.CurrentUICulture, ErrorMessageString, name); | |
} | |
public override bool IsValid(object value) | |
{ | |
return value == null || Enum.IsDefined(Type, value); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment