Skip to content

Instantly share code, notes, and snippets.

@danielmackay
Created November 16, 2013 06:53
Show Gist options
  • Save danielmackay/7496827 to your computer and use it in GitHub Desktop.
Save danielmackay/7496827 to your computer and use it in GitHub Desktop.
Web Api enumeration validation attribute. #webapi, #enum
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