Reputation: 3914
Possible duplicate of this question
But i tried that step (I received via POST) and didn't get success.
My globalization setting is <globalization uiCulture="en-in" culture="en-in"/>
and Template Code is
@model DateTime?
@Html.TextBox(
"",
Model.HasValue ? @ViewData.TemplateInfo.FormattedModelValue : "",
new { @class = "date" })
And meta data code
[DisplayFormat(DataFormatString = "{0:dd/MM/yyyy}",
ApplyFormatInEditMode = true)]
[DisplayName("Employee Hire Date")]
public DateTime HireDate { get; set; }
and this is the js i am using
<script type="text/javascript">
$(function () {
$("input:text.date").datepicker({ dateFormat: "dd/mm/yy" });
});
</script>
It accepts the Date range as,
11/01/2015
7/05/2015
12/04/2015
But if i given this
30/04/2015
model validation fails.
Couldn't figure out the fix for this. I started learning MVC as a beginner. So please bear this question. Please help me.
UPDATE
If i change my js code like this $(function () { $("input:text.date").datepicker({ dateFormat: "dd/MM/yy" }); });
but the format changes to
'30/April/2015'
which i don't want.
Upvotes: 1
Views: 1331
Reputation: 3914
Stephens Answer is right. Still i modified the script like this to make jquery.validate to work
$.validator.methods.date = function (value, element) {
return this.optional(element) || $.datepicker.parseDate("dd/mm/yy", value);
}
I guess there is no difference between these two. Still this one is working and this
$.validator.addMethod('date', function (value, element) {
if (this.optional(element)) {
return true;
}
var valid = true;
try {
$.datepicker.parseDate('dd/mm/yy', value);
}
catch (err) {
valid = false;
}
return valid;
});
is not working.
Please if some one finds out tel me.. Thanks !!
Upvotes: 0
Reputation:
The error occurs because jquery.validate.js
validates the date by using the javascript date constructor (new Date(value)
) which fails. You can use the jquery globalize plugin or you can override the jquery.validate
method by adding the following script (assuming this is the jqueryUI datepicker)
<script>
// do NOT wrap in document.ready
$.validator.addMethod('date', function (value, element) {
if (this.optional(element)) {
return true;
}
var valid = true;
try {
$.datepicker.parseDate('dd/mm/yy', value);
}
catch (err) {
valid = false;
}
return valid;
});
</script>
Side notes:
ApplyFormatInEditMode = true
is only applicable when using
EditorFor()
to generate the browsers implementation of the HTML5
datepicker (in which case it would need to be DataFormatString = "{0:yyyy-MM-dd}
anyway) so it can be removed.@Html.TextBoxFor(m => m.HireDate, "{0:dd/MM/yyyy}", new { @class = "date" })
Upvotes: 2