LSTANCZYK
9/25/2017 - 1:30 AM

Web Api enumeration validation attribute. #webapi, #enum

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);
        }
    }
}