I need to capture date and time both for my model property. In my model class I have the following
[Required]
[DataType(DataType.DateTime)]
public DateTime?
This works for me on both client and server side, I have moment.js installed too.
$("#datepicker").datepicker();
$('#datepicker').datepicker("option", "dateFormat", "dd/mm/yy");
$.validator.methods.date = function (value, element) {
return this.optional(element) || moment(value, "DD/MM/YYYY", true).isValid();
}
localization or moment.js was not work for me while using datetimepicker. splitting hour and then checking is working. I am using format: 'dd.mm.yyyy hh:ii' for datetimepicker.
$.validator.methods.date = function (value, element) {
var dateL = value.split(" ");
var date = dateL[0].split(".");
var hour = dateL.length > 1 ? dateL[1].split(":") : "";
return this.optional(element) || !/Invalid|NaN/.test(dateL.length > 1 ? new Date(date[2], date[1], date[0],hour[0],hour[1]).toString() : new Date(date[2], date[1], date[0]).toString());
}
I added the fix for date format parser, but I needed to set the format to 'L' so it could be work in all Locales:
$(function () {
$.validator.methods.date = function (value, element) {
return this.optional(element) || moment(value, "L", true).isValid();
}
});
Replace the content for this:
var isChrome = /Chrome/.test(navigator.userAgent) && /Google Inc/.test(navigator.vendor);
return this.optional(element) || (isChrome ? moment(value, 'L').isValid() : !/Invalid|NaN/.test(new Date(value)));
I have to validate dd/mm/yyyy hh:ii
and with help of @lukyer answer i have added
DD/MM/YYYY HH:mm
and it is working fine
Hope this help !
if you use JQuery unubtrosive validation you can add rules like behind and to change client-side validation message.
$('#inputName').rules('add',{
messages:{
date:'Invalid format date'
}
})