JS日期验证增强

时间:2012-04-09 19:21:01

标签: javascript validation date

我继承了以下脚本,需要对其进行改进。该功能检查仅输入允许的字符(0123456789 /),然后格式化为1/1/12输入的日期将重新格式化为01/01/2012。经过一点调整后,这部分工作得很好。我现在需要进一步进行验证,如果省略则添加年份,这意味着如果用户输入1/1,则需要格式化并添加当前年份(例如01/01/2012)。

用户输入和所需(工作)输出的示例

  • a / a /一个错误的警报用户 - 检查
  • 1/2/10更新输入字段以读取为01/03/2010
  • 01/01/12更新输入字段以读取为01/01/2012
  • 1/10/2更新输入字段以读取为01/10/2002

所需更新(除上述内容外) 1/9更新输入字段以读取为01/09/2012

这是当前的功能(只要保留上述功能,欢迎您更改,重写,等等)。 jQuery 1.7库正在使用中,可以实现。

function ValidateDate(obj)
{
/************************************************
DESCRIPTION: Validates that a string contains only 
    valid dates with 2 digit month, 2 digit day, 
    4 digit year. Date separator has to be /
    Uses combination of regular expressions and 
    string parsing to validate date.
    Ex. mm/dd/yyyy

PARAMETERS:
   ValidateDate(strValue) - String to be tested for validity

RETURNS:
   True if valid, otherwise false.

REMARKS:
   Avoids some of the limitations of the Date.parse()
   method such as the date separator character.
*************************************************/
    var checkOK = "0123456789/";
    var checkStr = obj.value;
    var allValid = true;
    var p = /(\d{1,2})\/(\d{1,2})\/(\d{1,4})/;
    var objRegExp = /^\d{1,2}(\-|\/|\.)\d{1,2}\1\d{4}$/;
    // check to see if valid characters were used       
    for (i = 0;  i < checkStr.length;  i++)
    {
        ch = checkStr.charAt(i);
        for (j = 0;  j < checkOK.length;  j++)
          if (ch == checkOK.charAt(j))
            break;
        if (j == checkOK.length)
        {
            allValid = false;
            break;
        }
    }
    if (!allValid)
    {
        alert("Please use only a combination of " + checkOK + "\'s charaters in the date field.  Dates should be entered in the format of mm/dd/yyyy.");
        setTimeout((function() { obj.select() }), 0);
        return (false);
    }       
    //  converts to mm/dd/yyyy format
    if (!obj.value.match(p)) return;
    num=new Array();
    num=obj.value.match(p);
    if (num[1].length == 1) num[1]="0" + num[1];
    if (num[2].length == 1) num[2]="0" + num[2];
    if (num[3].length == 1) num[3]="200" + num[3];
    if (num[3].length == 2) num[3]="20" + num[3];
    obj.value= num[1] + "/" + num[2] + "/" + num[3];
    //check to see if in correct format
    if(!objRegExp.test(obj.value))
    {
        alert('The date entered is not properly formatted.');
        return false; //doesn't match pattern, bad date
    }
    else{
        var arrayDate = obj.value.split(RegExp.$1); //split date into month, day, year
        var intDay = parseInt(arrayDate[1],10); 
        var intYear = parseInt(arrayDate[2],10);
        var intMonth = parseInt(arrayDate[0],10);
    //check for valid month
    if(intMonth > 12 || intMonth < 1) {
        alert('The date entered is invalid');
        return false;
    }

    //create a lookup for months not equal to Feb.
    var arrayLookup = { '01' : 31,'03' : 31, '04' : 30,'05' : 31,'06' : 30,'07' : 31,
                        '08' : 31,'09' : 30,'10' : 31,'11' : 30,'12' : 31}

    //check if month value and day value agree
    if(arrayLookup[arrayDate[0]] != null) {
      if(intDay <= arrayLookup[arrayDate[0]] && intDay != 0)
        return true; //found in lookup table, good date
    }

    //check for February
    var booLeapYear = (intYear % 4 == 0 && (intYear % 100 != 0 || intYear % 400 == 0));
    if( ((booLeapYear && intDay <= 29) || (!booLeapYear && intDay <=28)) && intDay !=0)
        return true; //Feb. had valid number of days
    }
    alert(obj.value + ' is not a valid date.');
    //  return false; //any other values, bad date
}

1 个答案:

答案 0 :(得分:0)

反对意见:

  • 您不必检查有效字符,因为您的匹配正则表达式已经需要它们。如果你真的想,请使用/^[\d\/]*$/.test()代替那个循环。
  • 要匹配1/1等日期,请使用/\d{1,2}\/\d{1,2}(\/\d{1,4})?/作为p,然后执行num = obj.value.split("/")代替匹配的群组
  • 要验证日期,请查看javascript date validation using date object
  • 您还应该允许ISO日期格式YYYY-MM-DD,它由Date()本地解析