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]) );

} 
LCJ
  • 22,196
  • 67
  • 260
  • 418

3 Answers3

6

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

if(s.indexOf(' ') != -1)
{
    //space exists
}
Adil
  • 146,340
  • 25
  • 209
  • 204
1

you can test for any whitespace like

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

it will test any whitespace.

user160820
  • 14,866
  • 22
  • 67
  • 94
0

You may want to consider using a regexp to test your string's validity:

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]);
}

The regex does all this in one go:

  • checks that there are three fields separated by slashes
  • requires that the fields be numbers
  • allows day and month to be 1 or 2 digits, but requires 4 for the year
  • ensures that nothing else in the string is legal

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

Alnitak
  • 334,560
  • 70
  • 407
  • 495