I have an HTML page with a web form. Among other things, it includes the following form fields:
- Title - textbox
- SourceName - textbox
- Url - textbox
- FullText - textbox
- PublicationDate - textbox using jQuery datepicker UI
- StartDate - textbox using jQuery datepicker UI
- EndDate - textbox using jQuery datepicker UI
I am trying to implement the jQuery validator multiple field sample:
jQuery(document).ready(function() {
// a custom method for validating the date range
jQuery.validator.addMethod("dateRange", function() {
var date1 = new Date(jQuery("#StartDate").val());
var date2 = new Date(jQuery("#EndDate").val());
return (date1 < date2);
}, "Please check your dates. The start date must be before the end date.");
// a new class rule to group all three methods
jQuery.validator.addClassRules({
requiredDateRange: { required: true, date: true, dateRange: true }
});
// overwrite default messages
jQuery.extend(jQuery.validator.messages, {
required: "These fields are required",
date: "Please specify valid dates"
});
jQuery("#mainForm").validate({
submitHandler: function() {
alert("Valid date range.")
},
groups: {
dateRange: "StartDate EndDate"
},
rules: {
"Title": "required",
"SourceName": "required",
"Url": "required",
"FullText": "required",
"PublicationDate": "required",
"CategoryCount": {required: true, min: 1}
},
messages: {
"Title": "Please type in a headline.",
"SourceName": "Please select a source by typing a few letters and selecting from the choices that pop up.",
"Url": "Please paste or type in a web page link.",
"FullText": "Please paste in the full text of the source report.",
"PublicationDate": "Please provide a date of publication.",
"CategoryCount": "Please specify at least one category."
}
});
// Capture changes to the list of selected categories by
// storing the count in a hidden field.
jQuery(".categoryCheckbox").click(function() {
var count = new Number(jQuery("#CategoryCount").val());
if (jQuery(this).attr("checked") == true) {
count = count + 1;
} else {
count = count - 1;
}
if (count < 0) {
count = 0
};
jQuery("#CategoryCount").val(count);
});
});
It validates all but the date range. I tried doing this a little more custom, but explicitly creating the Date objects prior to the return statement (in the demo, it's all on one line), but this did no good. Does anyone have experience making this actually work?
EDIT: I added a line to pop up an alert message when the dateRange method is called, but it never shows up. I wonder if the groups and rules parts of the validator just don't work together.