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?

4
  • Look at moment.js. It is a javascript framework for these situations Commented Feb 18, 2015 at 21:42
  • 1
    I am using moment.js, it also thinks 'hello 1' is a date. Commented Feb 18, 2015 at 21:52
  • i searched Stack Overflow and found this: stackoverflow.com/questions/13230360/… Commented Feb 18, 2015 at 22:09
  • What don't you want to accept? Should "jan 1" be ok, or do you want to reject anything with letters? Commented Feb 18, 2015 at 22:38

4 Answers 4

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")
Sign up to request clarification or add additional context in comments.

3 Comments

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.
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"))
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.
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"]

1 Comment

This forces me to know the date format, so won't work. However, awesome info about the parsingFlags stuff, thanks.
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

6 Comments

Sorry, running that console log returns true, not false.
This solution forces a date format with no spaces. In this case, using the return value of new Date() also returns false when passed into your function.
Try this time.. :P , Its full proof now... jsfiddle.net/voidSO/kux0246j/1
Fool proof, unless you pass anything but a string into that function. Otherwise, yes, it seems to work. Still, feels very dirty. Will accept after I do a bit more digging.
This also excludes "jan 1" (for example). Should it?
|
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);
}

3 Comments

Your first solution restricts the date formats, and the second doesn't solve the core issue. new Date("hello 1") is a valid date.
Yes i see it, I have done a correction, could you give it a try please?
Forget it, it still has problems. I'll tell you when I get it working

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.