Search code examples
c#asp.net-mvcasp.net-mvc-5

MVC 5 How to Validate Nullable Integers


This has been asked and answered numerous times, but I have a special situation where I have nullable integers in my model.

Model:

[Range(0, int.MaxValue, ErrorMessage = "Please enter valid integer number")]
public int? Jan { get; set; }

In my edit form, if enter "x", then the browser default error pop-up with "Please enter a number" appears. My own client-side validation doesn't appear to be kicking in. If I enter nothing, then it blows up server-side because a parameter was expected in my repository code.

I need it to validate non-integers on the client and I also need it to handle nulls, when someone tries to submit the form with an empty value. I cannot resort to a Required data annotation, because if I do, no data will be loaded. This is a conversion from legacy code to MVC.

UPDATE - CLARIFICATION:

I'm dealing with a lot of nullable ints. The decision to try and make them required was mine - am open to alternative options. I cannot change the int? in the model for various reasons. So, I need to validate against nulls on the client and server to ensure that integers are entered.


Solution

  • You can use the HTML5 required attribute client side to prevent empty values from being entered. If you really want to ensure no empty values are sent to the server, I believe you are going to need to do some server side validation as well.

    HTML5 Required Attribute