Link to home
Start Free TrialLog in
Avatar of -Dman100-
-Dman100-Flag for United States of America

asked on

isDate function - isolate for specific years

I'm using a javascript function that has a regular expression that checks for valid dates.  The regular expression works pretty well, howeer, one of the problems is that if a user makes a typo and enters a date way into the future it will cause an error.

For example, say, the user accidentally types in 5/5/9011.  That is actually a valid date, but it will cause an error.

So, I was wanting to modify the regular expression to isolate the years from say 1900 to 2100...two hundred years.

I'm not very good with regular expressions, so I was hoping some regex guru couild help with how to isolate those years in the following javascript function that uses the regex.

See the function below.

Thanks for any help.
function isDate(value)
{
   var dateRegEx = new RegExp(/^(?:(?:(?:0?[13578]|1[02])(\/|-)31)|(?:(?:0?[1,3-9]|1[0-2])(\/|-)(?:29|30)))(\/|-)(?:[1-9]\d\d\d|\d[1-9]\d\d|\d\d[1-9]\d|\d\d\d[1-9])$|^(?:(?:0?[1-9]|1[0-2])(\/|-)(?:0?[1-9]|1\d|2[0-8]))(\/|-)(?:[1-9]\d\d\d|\d[1-9]\d\d|\d\d[1-9]\d|\d\d\d[1-9])$|^(0?2(\/|-)29)(\/|-)(?:(?:0[48]00|[13579][26]00|[2468][048]00)|(?:\d\d)?(?:0[48]|[2468][048]|[13579][26]))$/);
 
   if (dateRegEx.test(value))
   {
      return true;
   }
   return false;
}

Open in new window

ASKER CERTIFIED SOLUTION
Avatar of cmalakar
cmalakar
Flag of India image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of HonorGod

Something like this perhaps?
function isDate( value ) {
  var result = /^[01]?\d\/(([0-2]?\d{1})|([3][0,1]{1}))\/((19\d{2})|(20\d{2})|(2100))$/.test(value)
//  alert( result )
  return result
}

Open in new window

This does the trick i guess
^([1-9]|0[1-9]|1[0-9]|2[0-9]|3[01])[/._-](0[1-9]|1[0-2])[/._-](19[0-9][0-9]|20[0-9][0-9])$
Please note, however, that this RegExp allows "invalid" dates, like Feb 31st...

For more detail about JavaScript dates, please take a look at this article:

https://www.experts-exchange.com/A_484.html
sorry code view is here

 
^([1-9]|0[1-9]|1[0-9]|2[0-9]|3[01])[/._-](0[1-9]|1[0-2])[/._-](19[0-9][0-9]|20[0-9][0-9])$

Open in new window


and if you wish to change restriction just change the part i ' underlined

^([1-9]|0[1-9]|1[0-9]|2[0-9]|3[01])[/._-](0[1-9]|1[0-2])[/._-](19[0-9][0-9]|20[0-9][0-9])$
Off-topic, but why not just return the value returned by "test()"?
function isDate(value)
{
   ...
 
   return dateRegEx.test(value);
}

Open in new window

SOLUTION
Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial