【发布时间】:2009-11-05 16:53:17
【问题描述】:
我有一个带有 Web 表单的 HTML 页面。除其他外,它包括以下表单字段:
- 标题 - 文本框
- SourceName - 文本框
- 网址 - 文本框
- 全文 - 文本框
- PublicationDate - 使用 jQuery 日期选择器 UI 的文本框
- StartDate - 使用 jQuery datepicker UI 的文本框
- EndDate - 使用 jQuery datepicker UI 的文本框
我正在尝试实现 jQuery 验证器多字段 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);
});
});
它会验证除日期范围之外的所有内容。我尝试更自定义地执行此操作,但在 return 语句之前显式创建 Date 对象(在演示中,它都在一行上),但这没有好处。有没有人有过让这件事真正发挥作用的经验?
编辑: 我添加了一行以在调用 dateRange 方法时弹出警告消息,但它从未出现过。我想知道验证器的组和规则部分是否不能一起工作。
【问题讨论】:
标签: jquery date validation