Login | Register   
LinkedIn
Google+
Twitter
RSS Feed
Download our iPhone app
TODAY'S HEADLINES  |   ARTICLE ARCHIVE  |   FORUMS  |   TIP BANK
Browse DevX
Sign up for e-mail newsletters from DevX


Tip of the Day
Language: Web
Expertise: Intermediate
Jul 30, 2002

Validate the Date Using JavaScript Regular Expressions


Regular Expressions provide a very powerful and easy method of client side validation. They are also both supported by IE and Netscape. It takes a lot less code, and works on every browser. Here's a simple date validation in Javascript—using regular expressions.
 
function validateDate(input)
{
  var datePattern = /^(\d{2})\/(\d{2})\/(\d{4})$/;
  if(!datePattern.test(input))
  {
    alert("Error... please enter date in mm/dd/yyyy format");
    return false;
  }
  var month = parseInt(RegExp.$1);
  if(month <=0 || month > 12)
  {
    alert("Error.. invalid month");
    return false;
  }
  var year = parseInt(RegExp.$3);
  var daysArray = new Array(31,28,31,30,31,30,31,31,30,31,30,31);
  if(year % 4 == 0)
  {
    daysArray[1] = 29;
  }
  var date = parseInt(RegExp.$2);
  if(date <=0 || date > daysArray[month-1])
  {
    alert("Error... invalid date");
    return false;
  }
  return true;
}
Ruchi Dhar
 
Comment and Contribute

 

 

 

 

 


(Maximum characters: 1200). You have 1200 characters left.

 

 

Sitemap
Thanks for your registration, follow us on our social networks to keep up-to-date