Date Validation Check (dd MMM yyyy) (JavaScript)

By below function you can check that your given date format is valid or invalid. Correct date format for this function is “11 Mar 1889”.

Function Declaration : 

function DateValidation(InputDate)
{
var MonthArray = [“Jan”,”Feb”,”Mar”,”Apr”,”May”,”Jun”,”Jul”,”Aug”,”Sep”,”Oct”,”Nov”,”Dec”];
var sInputDate = InputDate.split(” “);
var dateLength =  sInputDate[0].length;
var monthLength = sInputDate[1].length;
var trimYear = $.trim(sInputDate[2]);
var yearLength =  trimYear.length;
var monthNumber=0;
var result = “”;
if(parseInt(dateLength)!=2 || parseInt(monthLength)!=3 || parseInt(yearLength)!=4 || parseInt(trimYear)<2000)
{
result = “Invalid Date”;
}
if(result != “Invalid Date”)
{
for(var i=0; i<MonthArray.length; i++)
{
var makeUpperCase = sInputDate[1].toUpperCase();
if(makeUpperCase == MonthArray[i].toUpperCase())
{
result = “Valid Month”;
monthNumber = (i+1);
break;
}
else
{
result = “Invalid Date”;
}
}
}
if(result == “Valid Month”)
{
var year = parseInt(trimYear);
var month = monthNumber;
var days = Math.round(((new Date(year, month))-(new Date(year, month-1)))/86400000);
if(parseInt(sInputDate[0]) < 0 || parseInt(sInputDate[0]) > days)
{
result = “Invalid Date”;
}
else
{
result = “Valid Date”;
}
}
if(result == “Valid Date”)
{
var sInputDate = InputDate.split(” “);
sInputDate[1] = CapitaliseFirstLetter(sInputDate[1]);
result = sInputDate[0] + ” ” + sInputDate[1] + ” ” + sInputDate[2];
}
return result;
}

function CapitaliseFirstLetter(string)
{
var result = string.charAt(0).toUpperCase() + string.slice(1).toLowerCase();
return result;
}

Leave a Reply