Search code examples
asp.net-mvcmodelstateasp.net-mvc-validation

Asp.net MVC nullable DateTime model state validation


In my view model, i have a nullable DateTime property called BirthDate.

When i submit an invalid DateTime value to the controller, the ModelState.IsValid is false, saying that the BirthDate is an invalid DateTime.

How can i make ModelState to treat invalid nullable DateTime as a null value, instead of making it invalid?


Solution

  • ModelState is bit bothersome with DateTime because everytime your posted input doesn't match Datetime formatting .isValid() is going to be false.

    Have you considered using string to take in user input and later see if its possible to parse into DateTime.

    Ps. this also occurs when trying to post and empty string: C# MVC 4 ViewModel not accepting null DateTime

    Hope this helps :)