8

Im facing this error when im using my jQuery datepicker.

jQuery:

$( ".datepicker" ).datepicker({ 
    defaultDate: +7,
    autoSize: true,
    dateFormat: 'dd.mm.yy',
}); 

Model:

[DisplayName("Date")]
[DisplayFormat(DataFormatString = "{0:dd.MM.yyyy}", ApplyFormatInEditMode = true)]
[Required(ErrorMessage = "Date is required")]
public DateTime Date { get; set; }

So I want the date format to be like dd.MM.yyyy, and when I select the date using the datepicker it is correctly added to the field. But also in the same second, an validation error appears saying The field 'Date' must be a date.

I did test with writing manually the date in the format dd/MM/yy and then it looks like it is working. So somewhere the validator looks for that format, but I cant find out where to modify it.

Martin at Mennt
  • 5,677
  • 13
  • 61
  • 89

3 Answers3

2

Are you using chrome? Can be a jquery.validate.js issue, please have a look to this Jquery Datepicker Chrome

Community
  • 1
  • 1
D.Rosado
  • 5,634
  • 3
  • 36
  • 56
0

DisplayFormat won't be the format in which is accepted in the validation. I would suggest using a regular expression to validate this if you want something with periods in there.

[DisplayName("Date")]
[DisplayFormat(DataFormatString = "{0:dd.MM.yyyy}", ApplyFormatInEditMode = true)]
[Required(ErrorMessage = "Date is required")]
[RegularExpression(@"PUT REGEX HERE", ErrorMessage = "Invalid Date")] // below is a link
public DateTime Date { get; set; }

Some common expressions here.

Also, I would suggest being consistent in format when going from the c# to the js.

You have in JS:

dateFormat: 'dd.mm.yy'

You might want:

dateFormat: 'dd.mm.yyyy'

You could also just change the DisplayFormat attribute on the model to just be dd.MM.yy as well. Just a thought!

technicallyjosh
  • 3,511
  • 15
  • 17
0

Modifying the answer provided at https://stackoverflow.com/a/17968454/4955259 appears to be working for me for date format dd.mm.yy (add the script after jquery.validate.js).

jQuery.validator.methods.date = function (value, element) {
    var d = value.split(".");
    return this.optional(element) || !/Invalid|NaN/.test(new Date((/chrom(e|ium)/.test(navigator.userAgent.toLowerCase())) ? d[1] + "." + d[0] + "." + d[2] : value));
};
Community
  • 1
  • 1
davke
  • 350
  • 1
  • 7