Reputation: 167
PROBLEM:
I need to capture Date and Time data and I wrote this on my model class:
[Required(ErrorMessage = "Date of Birth cannot be empty")]
[Display(Name = "Date of Birth")]
public DateTime DateofBirth{ get; set; }
And I have this datepicker setting:
$('#DateofBirth').datepicker({
dateFormat: "dd MM yy",
changeMonth: true,
changeYear: true,
autoclose: true,
});
When I pick a date, the textbox validation always says: "The field Date of Birth must be a date". Even when I do not use datepicker (I write the date manually), it keeps saying like that.
I thought it has something to do with javascript or jquery as I read from many solutions offered. But, the validation keeps saying "The field Date of Birth must be a date".
After searching with no good results, I finally realized that date time format used by ASP.NET is DIFFERENT with the date time format used by jQuery. As this link says, the general DataFormatString for Date and Time is 6/15/2009 1:45:30 PM, so if I do not write exactly like that format, the validation error pops out. Even, when I use datepicker to fill the textbox.
Upvotes: 1
Views: 2372
Reputation: 167
SOLUTION:
Based on this link and this link I have to match the Date Time for for both ASP.NET model and jQuery datepicker.
So, I write custom Date Time format as dd MMMM yyyy in my model class:
[Required(ErrorMessage = "Date of Birth cannot be empty")]
[Display(Name = "Date of Birth")]
[DisplayFormat(ApplyFormatInEditMode = true, DataFormatString ="{0:dd MMMM yyyy}")]
public DateTime DateofBirth{ get; set; }
And the Date Time format as dd MM yy in jQuery datepicker properties, like this
$('#DateofBirth').datepicker({
dateFormat: "dd MM yy",
changeMonth: true,
changeYear: true,
autoclose: true,
});
I hope it helps.
Upvotes: 1