Required attribute for integer value

I have a viewmodel with Id property

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

But I think this attribute only works for string properties.

When Id is not set, Id is 0, and the model is valid.

How can I guarantee that if the value for the int property is not set, the model will be invalid?

+45
asp.net-mvc data-annotations
Jul 12 2018-11-11T00:
source share
2 answers

Change the type to Nullable<int> ( int? label int? ) To allow null values.

+35
Jul 12 2018-11-11T00:
source share

Use the Range attribute.

Set minimum 1 and maximum to int.MaxValue

 [Range(1, int.MaxValue, ErrorMessage = "Value for {0} must be between {1} and {2}.")] 
+56
Jul 12 '11 at 12:07
source share



All Articles