I am trying to create a custom validation method for my date time field, and i follow example at here: Jquery validate date range fails and here: Validate that end date is greater than start date with jQuery
Following is my form ( in mvc 3 razor partial view ):
@using (Html.BeginForm("CreateFood", "Stock", FormMethod.Post, new { id = "formData" }))
{
@Html.ValidationSummary(false, "Opps. Please correct the mistakes")
<div class="editor-label">
Storage Date
</div>
<div class="editor-field">
@Html.EditorFor(model => model.StorageDate, new { @class = "storedate" })
@Html.ValidationMessageFor(model => model.StorageDate)
</div>
<div class="editor-label">
Expiry Date
</div>
<div class="editor-field">
@Html.EditorFor(model => model.ExpiryDate, new { @class = "expirydate" })
@Html.ValidationMessageFor(model => model.ExpiryDate)
</div>
}
And the script:
jQuery.validator.addMethod("dateRange", function () {
var date1 = new Date(jQuery(".expirydate").val());
alert(date1);
var date2 = new Date(jQuery(".storedate").val());
alert(date2);
alert(date1 < date2);
return (date1 < date2);
}, "Please check your dates. The start date must be before the end date.");
$createdialog.dialog("option", "buttons", {
"Cancel": function () {
$createdialog.dialog('close');
},
"Submit": function () {
// Validate the form before ask for cabinet
var frm = $('#formData');
var validator = frm.validate({
rules: {
"ExpiryDate": { dateRange: true }
}
});
if (frm.valid()) {
submitForm();
}
Question:
-
I am not really sure about the syntax and what should I put at “ExpiryDate” (is it a selector? or is the form field name? ):
var validator = frm.validate({
rules: {
“ExpiryDate”: { dateRange: true }
} -
All the alert() in the method doesnt show, so I assume the method is never fire.. Any idea??
(PS: I am using datepicker for both date field with specific format as well:
$('.storedate').datepicker({ dateFormat: 'D, dd M yy' });
$('.expirydate').datepicker({ dateFormat: 'D, dd M yy' });
)
Really need help here… already been searching methods for few days just to implement the datetime validation…
Appreciate any feedback… Thanks…
});
These post series by Scott Allen, it may help you with a better approach.
http://odetocode.com/blogs/scott/archive/2011/02/21/custom-data-annotation-validator-part-i-server-code.aspx
http://odetocode.com/Blogs/scott/archive/2011/02/22/custom-data-annotation-validator-part-ii-client-code.aspx