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

前端 未结 2 1917
孤独总比滥情好
孤独总比滥情好 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:40

    There's EnumDataType in .NET4+ ...

    Make sure you set the 3rd parameter, validateAllProperties=true in the call to ValidateObject

    so from your example:

    public class Entity
    {
        [EnumDataType(typeof(MyEnum))]
        public MyEnum EnumValue { get; set; }
    }
    
    [Fact]
    public void TestInvalidEnumValue()
    {
        Entity entity = new Entity { EnumValue = (MyEnum)(-126) };
        // -126 is stored in the entity.EnumValue property
    
        Assert.Throws(() =>
            Validator.ValidateObject(entity, new ValidationContext(entity, null, null), true));
    }
    

提交回复
热议问题