0

I have following code that checks whether date is valid. http://jsfiddle.net/uzSU6/36/

If there is blank spaces in date part, month part or year part the date should be considered invalid. For this, currently I am checking the length of string before and after trim operation. It works fine. However is there a better method to check for white spaces? (For example, using === operator)

function isValidDate(s) 
{
var bits = s.split('/');

//Javascript month starts at zero
var d = new Date(bits[2], bits[0] - 1, bits[1]);


if ( isNaN( Number(bits[2]) ) ) 
{
    //Year is not valid number
    return false;
}

if ( Number(bits[2]) < 1 ) 
{
    //Year should be greater than zero
    return false;
}


//If there is unwanted blank space, return false
if  ( ( bits[2].length != $.trim(bits[2]).length ) ||
      ( bits[1].length != $.trim(bits[1]).length ) ||
      ( bits[0].length != $.trim(bits[0]).length ) )
{
    return false;
}



//1. Check whether the year is a Number
//2. Check whether the date parts are eqaul to original date components
//3. Check whether d is valid

return d && ( (d.getMonth() + 1) == bits[0]) && (d.getDate() == Number(bits[1]) );

} 
4

3 回答 3

6

You can use indexOf() function if there is space in the date string.

if(s.indexOf(' ') != -1)
{
    //space exists
}
于 2012-12-17T09:22:07.717 回答
1

您可以测试任何空格,例如

 if( /\s/g.test(s) )

它将测试任何空格。

于 2012-12-17T09:25:25.033 回答
0

您可能需要考虑使用正则表达式来测试字符串的有效性:

function isValidDate(s) {
    var re = /^(\d{1,2})\/(\d{1,2})\/(\d{4})$/;
    var mdy = s.match(re);
    if (!mdy) {
        return false;   // string syntax invalid;
    }

    var d = new Date(mdy[3], mdy[1] - 1, mdy[2]);
    return (d.getFullYear() == mdy[3]) &&
           (d.getMonth() == mdy[1] - 1) &&
           (d.getDate() == mdy[2]);
}

正则表达式一次性完成所有这些:

  • 检查是否存在由斜线分隔的三个字段
  • 要求字段为数字
  • 允许日期和月份为 1 或 2 位数字,但年份需要 4
  • 确保字符串中没有其他内容是合法的

http://jsfiddle.net/alnitak/pk4wU/

于 2012-12-17T09:25:18.450 回答