Skip to content

Instantly share code, notes, and snippets.

@LSTANCZYK
Forked from danielmackay/EnumModelValiation.cs
Created September 25, 2017 01:30
Show Gist options
  • Save LSTANCZYK/ef6ab7384a95e9182b5107d963a4c333 to your computer and use it in GitHub Desktop.
Save LSTANCZYK/ef6ab7384a95e9182b5107d963a4c333 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