Javascript / Time / Date / Date Validate
Snippet details
ID: 60
Viewed: 1826
Added: 2002-01-17
Version:
Sorry no demo
Function checks for valid date of the form dd/mm/yy or dd/mm/yyyy ( or ddmmyy, or d/m/yy etc.)
Utilizes the fact that Javascript will internally convert dodgy dates. eg. 2002,4,44 is June 13, 2002 (remembering that Javascript months go from 0 to 11).
<!---Head--->
<script>
function stringToDate(inStr) { // returns a date from input dd/mm/yyyy
if (!inStr) return false;
var reDate = /^s*(d{1,2})D*(d{1,2})D*(d{2,4})s*$/
var matchArray = reDate.exec(inStr);
if (!matchArray) return false;
// to check for mm/dd/yyyy, swap these next two lines
var tDay = parseInt(matchArray[1],10);
var tMonth = parseInt(matchArray[2],10);
var tYear = parseInt(matchArray[3],10);
if (isNaN(tDay + tMonth + tYear)) return false;
if (tYear.toString().length == 3) return false;
if (tYear.toString().length <= 2)
tYear += (tYear < 50) ? 2000 : 1900;
return isValidDate(tYear, tMonth - 1, tDay);
}
function isValidDate(inY,inM,inD) {
var testDate = new Date(inY, inM, inD);
if (!testDate) return false;
return ( testDate.getDate() == inD
&& testDate.getMonth() == inM
&& testDate.getFullYear() == inY) ? testDate : false;
}
</script>
<!---Body--->
<form>
<input type=text onchange="dateObject=stringToDate(this,value);">
</form>
No Reviews to show
