Is there out-of-the box validator for Enum values in DataAnnotations namespace?

前端 未结 2 1931
孤独总比滥情好
孤独总比滥情好 2021-01-04 03:37

C# enum values are not limited to only values listed in it\'s definition and may store any value of it\'s base type. If base type is not defined than Int32 or s

2条回答
  •  温柔的废话
    2021-01-04 03:44

    What you're looking for is:

     Enum.IsDefined(typeof(MyEnum), entity.EnumValue)
    

    [Update+1]

    The out of the box validator that does a lot of validations including this one is called EnumDataType. Make sure you set validateAllProperties=true as ValidateObject, otherwise your test will fail.

    If you just want to check if the enum is defined, you can use a custom validator with the above line:

        [AttributeUsage(AttributeTargets.Parameter | AttributeTargets.Field | AttributeTargets.Property | AttributeTargets.Method, AllowMultiple = false)]
        public sealed class EnumValidateExistsAttribute : DataTypeAttribute
        {
            public EnumValidateExistsAttribute(Type enumType)
                : base("Enumeration")
            {
                this.EnumType = enumType;
            }
    
            public override bool IsValid(object value)
            {
                if (this.EnumType == null)
                {
                    throw new InvalidOperationException("Type cannot be null");
                }
                if (!this.EnumType.IsEnum)
                {
                    throw new InvalidOperationException("Type must be an enum");
                }
                if (!Enum.IsDefined(EnumType, value))
                {
                    return false;
                }
                return true;
            }
    
            public Type EnumType
            {
                get;
                set;
            }
        }
    

    ... but I suppose it's not out of the box then is it?

提交回复
热议问题