fluentvalidationfluentvalidation-2.0

FluentValidation NotNull on enum values


I have a model with enum property which based on 'int'. I need to validate that this property is not empty. But NotEmpty forbids 0 value. And NotNull just doesn't work because enum property cannot be null. I cannot make my property nullable. How can I do such validation?


Solution

  • As long as the enum type is int you can do the following:

    public class Status
        {
            public StatusType type { get; set; }
        }
    
        public enum StatusType
        {
            open = 1,
            closed = 2
        }
    
        public class StatusValidator : AbstractValidator<Status>
        {
            public StatusValidator()
            {
                RuleFor(x => x.type).Must(x => x != 0);
            }
    
        }
    

    If you can't avoid 0 you can define a workaround for the model as follow (source: Choosing the default value of an Enum type without having to change values):

    [Note: you need to include using System.ComponentModel;]

    public class Status
    {
        public StatusType type { get; set; }
    }
    
    [DefaultValue(_default)]
    public enum StatusType
    {
        _default = -1,
        test = 0,
        open = 1,
        closed = 2,
    
    }
    
    public static class Utilities
    {
        public static TEnum GetDefaultValue<TEnum>() where TEnum : struct
        {
            Type t = typeof(TEnum);
            DefaultValueAttribute[] attributes = (DefaultValueAttribute[])t.GetCustomAttributes(typeof(DefaultValueAttribute), false);
            if (attributes != null &&
                attributes.Length > 0)
            {
                return (TEnum)attributes[0].Value;
            }
            else
            {
                return default(TEnum);
            }
        }
    }
    
    public class StatusValidator : AbstractValidator<Status>
    {
        public StatusValidator()
        {
            RuleFor(x => x.type).Must(x => x != Utilities.GetDefaultValue<StatusType>());
        }
    
    }