更新答案
响应 OP 在下面的评论...
在漫长的工作日结束后,我很快就把它整理好了,所以我为憔悴而道歉。可以在JS Bin 上找到完整的工作示例(带有大量注释)。这个例子展示了如何使用 jQuery UI 的 datepicker 和 tooltip 小部件结合输入字段的标准 oninput 事件来创建一个动态字段,该字段无需提交表单数据即可进行客户端表单验证。
我意识到这可能不是最优雅的方式,但我没有在这个论坛中看到过建议。 话说回来,这可能是有充分理由的......
不过,这里是对框架的快速浏览——要在“行动”中看到它,您可以查看它的JS Bin page。 请原谅格式,我现在对 CSS 太懒了。
// I've gone ahead and removed most of the code and notes for
// brevity. See: [http://jsbin.com/wuyum/1/edit?js,output]
$(function () {
// Internal function used to incrementally validate the user's
// input (valid for both mm/dd/yyyy & dd/mm/yyyy formats).
function validateInput(contents) {
var rgx = /^(\d{1,2}(?:\/(?:\d{1,2}(?:\/(?:\d{1,4})?)?)?)?)$/;
return rgx.test(contents);
};
// Internal function used to check a valid date format against
// a valid date (e.g. 99/99/2014 is not a valid date).
function checkDate(date) {
return !isNaN(new Date(date).getDate());
};
// Create a new datepicker object and use its onSelect event to
// run through your AJAX call...
$('#date').datepicker({
// onSelect will be called when the user either selects a date
// from the widget, or uses the Return/Enter key on submission.
onSelect: function (date) {
// By now the date has already been validated, client-side,
// in two-part. First the RegEx matched a mm/dd/yyyy format
// and then we confirmed that the date wasn't erroneous with
// checkDate(). If the user submitted an invalid date (say
// '44/44') the widget will automatically reset the date to
// 'today'. Alternatively, you could call checkDate() again
// during this event -- that's really your call.
// Execute your AJAX call
// $.ajax() ...
}
}).tooltip({
// Define a non-delegated tooltip to use as a prompt...
}).on('input', function () {
// Handle the forms RegExp and format validation here...
});
});
值得注意的是datepicker的默认格式是mm/dd/yyyy。这可以很容易地更改,但是应该警告您,如果您的目标是为用户提供输入mm/dd/yyyy 或dd/mm/yyyy 的选项,除非首先使用正在使用的格式进行验证,否则您将遇到一些问题。例如:
10/06/2014 --> October 6th 2014 (mm/dd/yyyy)
10/06/2014 --> June 10th 2014 (dd/mm/yyyy)
希望对你有所帮助。
原答案
从您的 RegEx 模式来看,您似乎正在尝试根据标准日期格式 mm/dd/yyyy 验证该字段。
如果是这种情况,并且您想在每次更改字段时验证格式,我建议使用jQuery UI 和Datepicker 小部件——利用datepickers onSelect 事件。像这样:
// where #date is the id of <input id="date" type="text"/>
$('#date').datepicker({
onSelect: function(date) {
// $.ajax() here
}
});
或者,您可以在 input 字段的 onchange 事件中管理 RegEx 验证和 AJAX 调用。
// obviously you'd want to be more specific than simply grabbing the first
// input element found.
document.getElementsByTagName('input')[0].onchange = function (e) { ... };
最后,您可以查看 HTML5 及其对 date type 属性的实现。