0

I am validating dates using regular expression in javascript. The regular expression I am using is

/^(((((0?[1-9])|(1\d)|(2[0-8]))\/((0?[1-9])|(1[0-2])))|((31\/((0?[13578])|(1[02])))|((29|30)\/((0?[1,3-9])|(1[0-2])))))\/((20[0-9][0-9])|(19[0-9][0-9])))|((29\/02\/(19|20)(([02468][048])|([13579][26]))))$/

This matches dates accurately but it would match values such as 1/1/2001ff even though I am using $ to mark the end of string. But if I give values like ff1/1/2001 it would invalidate it. So it's considering the start of the string and ignore the end of string part.

Does anyone know the reason for this.

Kasun Jayasinghe
  • 355
  • 1
  • 8
  • 21
  • 3
    Why do you need such a complicated regex with over 20 capturing groups for? http://www.myezapp.com/apps/dev/regexp/show.ws?regex=/%5E%28%28%28%28%280%3F%5B1-9%5D%29%7C%281%5Cd%29%7C%282%5B0-8%5D%29%29%5C/%28%280%3F%5B1-9%5D%29%7C%281%5B0-2%5D%29%29%29%7C%28%2831%5C/%28%280%3F%5B13578%5D%29%7C%281%5B02%5D%29%29%29%7C%28%2829%7C30%29%5C/%28%280%3F%5B1%2C3-9%5D%29%7C%281%5B0-2%5D%29%29%29%29%29%5C/%28%2820%5B0-9%5D%5B0-9%5D%29%7C%2819%5B0-9%5D%5B0-9%5D%29%29%29%7C%28%2829%5C/02%5C/%2819%7C20%29%28%28%5B02468%5D%5B048%5D%29%7C%28%5B13579%5D%5B26%5D%29%29%29%29%24/&env=env_js – Samuel Liew May 06 '13 at 06:57
  • 1
    You can't really validate dates reliably with regex, just the format. Try to validate `11/31/13` as invalid for example. It's way easier if you use the `Date` object. – elclanrs May 06 '13 at 06:58
  • Don't have time to go over it fully. But a quick look at your regex on http://www.debuggex.com/ make it look like your only checking end of line on leap years (missing bracket by the sound of it). – Dracs May 06 '13 at 07:00
  • Tested on rubular, and seems to work – Casimir et Hippolyte May 06 '13 at 07:04

2 Answers2

2

From: Detecting an "invalid date" Date instance in JavaScript

if ( Object.prototype.toString.call(d) === "[object Date]" ) {
  // it is a date
  if ( isNaN( d.getTime() ) ) {  // d.valueOf() could also work
    // date is not valid
  }
  else {
    // date is valid
  }
}
else {
  // not a date
}

Logically, it makes much more sense to check if the date is valid rather than using a regex to match a date. However, if you're trying to search for dates, your regex still works (I tested it in Notepad++ find for example.) Other than that, like the comment said, there's no reason to have such a complicated regex.

Community
  • 1
  • 1
  • Unless I'm strongly mistaken, this expects an already *existing* Date object as `d`, the OP however only has a string. – phant0m May 06 '13 at 08:07
0

As correctly pointed out by Dracs, the issue was with missing brackets. Thank you very much for pointing that out. The reason for not using javascript date object is we need only to allow mm/dd/yyyy format in the textbox. So it would be easy to use a regex to validate textbox.

Kasun Jayasinghe
  • 355
  • 1
  • 8
  • 21