2

Does anyone know of any way to check if strings are valid dates? I'm trying to block against invalid dates, while not forcing any kind of date format. Basically here's the problem:

!!Date.parse('hello 1') === true

Javascript can figure out a date from that string, therefore, it's a date. I'd rather it not be. Anyone?

Zachary Nicoll
  • 339
  • 1
  • 4
  • 14

4 Answers4

2

Since you're using moment.js, try using parsingFlags():

var m = moment("hello 1", ["YYYY/MM/DD"]).parsingFlags();
if (!m.score && !m.empty) {
    // valid
}

It's the metrics used for isValid() and you can use them to make a stricter validation function.

Note: You can specify the other formats to support in the second argument's array.

Some other properties returned by parsingFlags() that might be of interest are the following:

  • m.unusedInput - Ex. ["hello "]
  • m.unusedTokens - Ex. ["MM", "DD"]
David Sherret
  • 101,669
  • 28
  • 188
  • 178
2

How close would stripping out spaces around words get you? It at least weeds out "hello 1" and such.

Date.parse('hello 1'.replace(/\s*([a-z]+)\s*/i, "$1")); // NaN
Date.parse('jan 1'.replace(/\s*([a-z]+)\s*/i, "$1")); // Valid

[update] Ok, so we'll just replace any non-alphanumerics that fall between a letter and a number:

replace(/([a-z])\W+(\d)/ig, "$1$2")
Roy J
  • 42,522
  • 10
  • 78
  • 102
  • Very close. The only thing this doesn't cover is checking the return value of `new Date()`. Using this logic, it says it's NaN. – Zachary Nicoll Feb 18 '15 at 22:53
  • I mean if we pass the return value of new Date(), it fails. So `Date.parse("Wed Feb 18 2015 17:59:11 GMT-0500 (EST)".replace(/\s*([a-z]+)\s*/i, "$1"))` – Zachary Nicoll Feb 18 '15 at 22:59
  • 1
    I upvoted this answer because it works in most situations and is good enough, but just wanted to point out it doesn't say text like the following is invalid: `Date.parse('Any words for Jane 1'.replace(/([a-z])\W+(\d)/ig, "$1$2")) == 978325200000`. It seems that just the end of the string has to be valid. – David Sherret Feb 23 '15 at 21:02
0

Use this function to check date

  function isDate(s)
{   
  if (s.search(/^\d{1,2}[\/|\-|\.|_]\d{1,2}[\/|\-|\.|_]\d{4}/g) != 0)
     return false;
  s = s.replace(/[\-|\.|_]/g, "/"); 
  var dt = new Date(Date.parse(s)); 
  var arrDateParts = s.split("/");
     return (
         dt.getMonth() == arrDateParts[0]-1 &&
         dt.getDate() == arrDateParts[1] &&
         dt.getFullYear() == arrDateParts[2]
     );   
}

console.log(isDate("abc 1")); // Will give false

Working Fiddle

void
  • 36,090
  • 8
  • 62
  • 107
0

It would be ok if you check for several types of dates?

kind of this for narrow the permited dates:

if( givenDate.match(/\d\d\/\d\d\/\d\d\d\d/)
|| givenDate.match(/\w*? \d{1,2} \d{4}/)
|| givenDate.match(anotherFormatToMatch) )

UPDATED

Or, althougt it restrict characters, you coud use something like this:

function myFunction() {
    var str = "The rain in SPAIN stays mainly in the plain"; 
    var date = new Date(str);
    if (date != "Invalid Date" && !isNaN(new Date(date) && !str.match(/a-z/g) )
        alert(date);
}
chomsky
  • 300
  • 3
  • 13