Reputation: 5737
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.
Upvotes: 8
Views: 18409
Reputation: 360
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));
};
Upvotes: 0
Reputation: 5773
Are you using chrome? Can be a jquery.validate.js issue, please have a look to this Jquery Datepicker Chrome
Upvotes: 2
Reputation: 3531
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; }
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!
Upvotes: 0