RegEx Short Date Validation (14-Mar-98)

Here's a little JavaScript function to validate short date formatted values (14-Mar-98). Just pass in the form element and let the function to the rest. Checks for valid format as well as valid days, months, and years.

Here's a little JavaScript function to validate short date formatted values (14-Mar-98). Just pass in the form element and let the function to the rest. Checks for valid format as well as valid days, months, and years.


function ValidateShortDate(oField)
{
/*
validates an input field for dates formatted as dd-Mth-yy or (14-Mar-03)
*/

var sDate = oField.value.toUpperCase();
var bValid = false;
var aMatch =/^\d{2}[\/-](JAN|FEB|MAR|APR|MAY|JUN|JUL|AUG|SEP|OCT|NOV|DEC)[\/-]\d{2}$/.exec(sDate);

if (sDate.length==0) { return true; }

if (aMatch == null)
{
alert(sDate + " is not in 14-Mar-03 format."); oField.focus();
oField.value='';
return bValid;
}

var DateArray = sDate.split("-");

// Convert the text month to a number - zero based month

switch (DateArray[1])
{
case "JAN": DateArray[1] = 0; break;
case "FEB": DateArray[1] = 1; break;
case "MAR": DateArray[1] = 2; break;
case "APR": DateArray[1] = 3; break;
case "MAY": DateArray[1] = 4; break;
case "JUN": DateArray[1] = 5; break;
case "JUL": DateArray[1] = 6; break;
case "AUG": DateArray[1] = 7; break;
case "SEP": DateArray[1] = 8; break;
case "OCT": DateArray[1] = 9; break;
case "NOV": DateArray[1] = 10; break;
case "DEC": DateArray[1] = 11; break;
}

// Use 1970 as the breaking point for determining whether the year
// should be >= 2000 or 1900.

if (DateArray[2] < 70) { DateArray[2] = 20 + DateArray[2]; }
else { DateArray[2] = 19 + DateArray[2]; }

var oDate = new Date();

oDate.setFullYear(DateArray[2]);
oDate.setMonth(DateArray[1]);
oDate.setDate(DateArray[0]);

// Validate whether the date itself is a valid calendar date.

if ((DateArray[2] != oDate.getFullYear()) || (DateArray[1] != oDate.getMonth()))
{
oField.value='';
alert(sDate + " has the right format, \n" + "but is not a valid calendar date.");
return bValid;
}


bValid = true;
return bValid;
}


Submission Date:  9/23/2005 2:55:34 PM
Submitted By:  Robbe Morris
My Home Page:  http://www.robbemorris.com

By Robbe Morris   Popularity  (441 Views)
Picture
Biography - Robbe Morris
Robbe has been a Microsoft MVP in C# since 2004. He is also the co-founder of NullSkull.com which provides .NET articles, book reviews, software reviews, and software download and purchase advice.  Robbe also loves to scuba dive and go deep sea fishing in the Florida Keys or off the coast of Daytona Beach. Microsoft MVP