2

I am trying to display a friendly error message on form validation. I have a property with annotations in the model class:

[Required(ErrorMessage="The number attribute is required")]
public int Level { get; set; }

It does not work, but when I change the data type to string, the annotation's error message is displayed. Does this mean that int is not supported?

John Doe
  • 1,364
  • 1
  • 12
  • 19
  • [int is a value type so is never null](http://stackoverflow.com/questions/5057267/what-is-the-difference-between-a-reference-type-and-value-type-in-c) – Liam Sep 02 '16 at 10:32

2 Answers2

6

You will getting a 0 through, which is why the validation is appearing to not work for that type - 0 is a value.

Try changing the type to a nullable int (int?) and it should then be fine.

AdaTheDev
  • 142,592
  • 28
  • 206
  • 200
0

If user's input is an empty string then the value is converted to null. Null value cannot be assigned to an int type variable. Therefore, an error is already thrown when binding null value to the int variable before even reaching EF validation. So the [Required(ErrorMessage="The number attribute is required")] code is not executed.

Using nullable int (int?) accepts user's null and empty value. Subsequently, EF validation will be executed and you can perform "no empty input" validation by using [Required] annotations.

kennykee
  • 116
  • 2
  • 7