I have a viewmodel with an Id property
[Required] public int Id { get; set; }
But I think this attribute is working only for string properties.
When no Id is set, Id has value 0 and the model is valid.
How can I enforce that if no value for a int property is set, the model will be invalid ?
The Required attribute indicates that a property must have a value; in this sample, a movie has to have values for the Title , ReleaseDate , Genre , and Price properties in order to be valid. The Range attribute constrains a value to within a specified range.
The Required attribute is used to specify that the value cannot be empty.
Use the Range
Attribute.
Set minimum to 1 and maximum to int.MaxValue
[Range(1, int.MaxValue, ErrorMessage = "Value for {0} must be between {1} and {2}.")]
Change the type to Nullable<int>
(shortcut int?
) to allow null
values.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With