Kasun Jayasinghe
Kasun Jayasinghe

Reputation: 355

Javascript regular expression does not match till the end of the string

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.

Upvotes: 0

Views: 130

Answers (2)

Kasun Jayasinghe
Kasun Jayasinghe

Reputation: 355

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.

Upvotes: 0

user1508519
user1508519

Reputation:

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.

Upvotes: 2

Related Questions