Required attribute for an integer value

前端 未结 5 2212
遇见更好的自我
遇见更好的自我 2020-12-01 11:45

I have a viewmodel with an Id property

[Required]
public int Id { get; set; }

But I think this attribute is working only for string propert

5条回答
  •  情话喂你
    2020-12-01 12:14

    This is similar to the answer from @Lee Smith, but enables 0 to be valid input, which might be useful in some scenarios.

    What you can do is to init the int value to another value then 0, like this:

    [Range(0, int.MaxValue)]
    public int value{ get; set; } = -1;
    

    It would even be possible to support all values except int.MinValue by doing it like this:

    [Range(int.MinValue + 1, int.MaxValue)]
    public int value{ get; set; } = int.MinValue;
    

提交回复
热议问题