jQuery验证引擎:更改日期格式的正则表达式dd-M-yy

时间:2014-11-26 09:28:17

标签: javascript jquery regex validation

用于验证日期格式的JS脚本:

"date": {                    
                    //  Check if date is valid by leap year
            "func": function (field) {
                    //var pattern = new RegExp(/^(\d{4})[\/\-\.](0?[1-9]|1[012])[\/\-\.](0?[1-9]|[12][0-9]|3[01])$/);
                    var pattern = new RegExp(/([12]\d|0[1-9]|3[0-1])-(Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec)-\d{4}/);
                    var match = pattern.exec(field.val());
                    if (match == null)
                       return false;

                    /*var year = match[1];
                    var month = match[2]*1;
                    var day = match[3]*1;*/
                    var year = match;
                    var month = match[2];
                    var day = match[3];

                    var date = new Date(day, month - 1, year); // because months starts from 0.
                    return (date.getFullYear() == year && date.getMonth() == (month - 1) && date.getDate() == day);
                },                      
             "alertText": "* Invalid date, must be in DD-MM-YYYY format"
                },

此处,正则表达式已更改为使用格式dd-M-yy。正则表达式有效但在datepicker输入为true时仍显示验证错误。

如何将日期格式设为dd-M-yy,即26-Nov-2014,如果格式正确,则不提供验证?

感谢。

1 个答案:

答案 0 :(得分:0)

试试这个

var pattern = new RegExp(/([12]\d|0[1-9]|3[0-1])-(Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec)-(\d{4})/);
var match = pattern.exec(field.val());
if (match == null)
 return false;

var months = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"]
var year = match[3];
var month = match[2];
var day = match[1];

var date = new Date(day, month - 1, year); // because months starts from 0.
return (date.getFullYear() == year && date.getMonth() == months.indexOf(month) && date.getDate() == day);

<强> http://jsfiddle.net/mw56tnej/12/