In my MVC5 Razor code for entering Date of Birth I am using a datepicker as below
@Html.EditorFor(model => model.date_of_birth,
new { htmlAttributes = new { @class = "m-wrap datepicker" } })
Here for the model.date_of_birth
an EditorFor
is calling and making it as a datepicker
with @class = datepicker
Then the datepicker is initiated at the script area with below code
$('.datepicker').datepicker({
format: 'yyyy-mm-dd',
autoclose: true
})
Here the date format is 'yyyy-mm-dd'
and it is working fine, but the user want it to be in dd-mm-yyyy
format. So I changed the format in script as dd-mm-yyyy
In Internet Explorer it is working fine but in Chrome it is giving an error for some date
eg: 14-05-2015
The field Date of Birth* must be a date.
the date 11-05-2015
is working fine in chrome also. So I guess Chrome is taking the date format in mm-dd-yyyy
.
The format 'dd-M-yyyy'
is also working correctly only error coming for dd-mm-yyyy
Any way to overcome this browser specific error?
Edit
$.validator.addMethod('date', function (value, element) {
if (this.optional(element)) {
return true;
}
var valid = true;
try {
$.datepicker.parseDate('dd/mm/yyyy', value);
}
catch (err) {
valid = false;
}
return valid;
});
$(function () {
$('.datepicker').datepicker({
format: 'dd/mm/yyyy',
autoclose: true
})
});
At last I found a solution.
First I create a new java script file with name jquery.validate.date.js
with the below code in it
$(function () {
$.validator.methods.date = function (value, element) {
if ($.browser.webkit) {
var d = new Date();
return this.optional(element) || !/Invalid|NaN/.test(new Date(d.toLocaleDateString(value)));
}
else {
return this.optional(element) || !/Invalid|NaN/.test(new Date(value));
}
};
});
It overwrite the date validation function in jquery.validate.js
Then i call the script just after 'jquery.validate.js'
like below
<script type="text/javascript" src="@Url.Content("~/Scripts/jquery.val.js")"/>
<script type="text/javascript" src="@Url.Content("~/Scripts/jquery.val.date.js")"/>
Now the date format dd/mm/yyyy is working in both chrome and IE without any error.
There is a problem with unobtrusive validator for dates in non 'yyyy-MM-dd' format. Similar question is here.
Solving by disabling validation of dates
jQuery.validator.methods["date"] = function (value, element) { return true; }
or by using globalization.
In my case i always set input to readonly and add datepicker from jquery.ui. with localization.
@Html.TextBoxFor(model => model.date_of_birth,
new { htmlAttributes = new { @class = "m-wrap datepicker", @readonly="readonly" } })
and some js:
// include localization for datepicker
$( "#date_of_birth" )
.datepicker( $.datepicker.regional[ "ru" ] )
.datepicker({ dateFormat: 'dd-mm-yy' });
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With