-1

Im triying to validade a datetime field with inobstrusive validation.

If the input is 01/01/2017 10:00 then I get

The field [fieldId] must be a date.

However the field must not be a date, but a datetime.

The parameter is set like this in my model:

    [Display(Name = "Start")]
    [DataType(DataType.DateTime)]
    public DateTime start { get; set; }

I was not able to correctally validate a field with datetime input.

How can I do this?

Daniel Santos
  • 14,328
  • 21
  • 91
  • 174
  • The code you have shown will **not** result in a client side validation error for a value of `01/01/2017 10:00` (unless you have done something like overridden the `date` method in `$.validator`). If your getting a client side error, then it is because you have entered a value which is not a valid date. –  Feb 09 '17 at 04:36
  • It seems seems to be a culture error, even i set the correct culture in web.config, the client validation expect a MM/dd/yyyy date, not the culture localized one. – Daniel Santos Feb 09 '17 at 16:18
  • The culture in the server does not affect the browser. And by default `jquery.validate.js` validates dates in MM/dd/yyyy format. But `01/01/2017 10:00` does pass in either `MM/dd/yyyy` or `dd/MM/yyyy`). If on the other hand your entering say `20/1/2017` (20th January) then it will generate a client side error. If that is the case, you need to just need to reconfigure the validator. But that is not what you question states so if that is what your experiencing, edit the question and I can give you an answer to solve it. –  Feb 09 '17 at 20:07

1 Answers1

2

Keep in mind that specifying the DataType does not do validation. All it does is provide a hint to the browser as to what kind of input is expected. To validate, try adding a regular expression validator, like so:

[RegularExpression(@"^((((31\/(0?[13578]|1[02]))|((29|30)\/(0?[1,3-9]|1[0-2])))\/(1[6-9]|[2-9]\d)?\d{2})|(29\/0?2\/(((1[6-9]|[2-9]\d)?(0[48]|[2468][048]|[13579][26])|((16|[2468][048]|[3579][26])00))))|(0?[1-9]|1\d|2[0-8])\/((0?[1-9])|(1[0-2]))\/((1[6-9]|[2-9]\d)?\d{2})) (20|21|22|23|[0-1]?\d):[0-5]?\d$", ErrorMessage = "Date must be in the format of : dd/mm/yyyy hh:mm"]
[Display(Name = "Start")]
[DataType(DataType.DateTime)]
public DateTime start { get; set; }
Icemanind
  • 47,519
  • 50
  • 171
  • 296