19 Aralık 2019

Enum İçin Validation

//
public class DefinedEnumAttribute : ValidationAttribute
{
    protected override ValidationResult IsValid(object value, ValidationContext validationContext)
    {
        if (value != null)
        {
            if (Enum.IsDefined(value.GetType(), value))
            {
                return ValidationResult.Success;
            }
            else
            {
                return new ValidationResult($"Not valid enum type {value.GetType().Name}.");
            }
        }
        return new ValidationResult("" + validationContext.DisplayName + " is required");
    }
}
public enum OrderStatus
{
    OrderReceived = 0,
    Preparing = 1,
    Printing = 2,
    Ready = 3,
    Shipped = 4
}
public class OrderDto
{
    [DefinedEnum]
    public OrderStatus OrderStatus { get; set; }

}
//