Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Required attribute for an integer value

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 ?

like image 714
user256034 Avatar asked Jul 12 '11 10:07

user256034


People also ask

What is required attribute in C#?

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.

Which of the annotations specifies that the property with which this annotation is associated Cannot be left blank?

The Required attribute is used to specify that the value cannot be empty.


2 Answers

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}.")] 
like image 108
Lee Smith Avatar answered Sep 28 '22 07:09

Lee Smith


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

like image 39
Julien Lebosquain Avatar answered Sep 28 '22 07:09

Julien Lebosquain