Abundant Technologies - IT Consulting Experts

 Source Code Library

 Code Details

 
/************************************************************************************ '* Comments: Validate a date field mm/dd/yy or mm/dd/yyyy '* '* Parameters: oDateVal - element to be evaluated '* '* Requirements: Used with onblur event to validate before submit '* '* Returns: Nothing, alerts and erases field '* '* Author: Tom Kershner, Abundant Technologies '************************************************************************************/ function isDate(oDateVal){ var dArray; var mVal; var dVal; var yVal; var sSeparator; //Allow empty string, validate on submit if(oDateVal.value=="") return true dArray = dSplit(oDateVal.value, "/"); if (dArray.length == 3){ sSeparator="/" } else{ dArray = dSplit(oDateVal.value, "-"); if (dArray.length == 3){ sSeparator="-" } else{ dArray = dSplit(oDateVal.value, "."); if (dArray.length == 3){ sSeparator="." } else{ // invalid separator alert("Must enter a valid date. (mm/dd/yyyy)"); oDateVal.value=""; oDateVal.focus(); return false; } } } // Assign values mVal = parseInt(dArray[0], 10); dVal = parseInt(dArray[1], 10); yVal = parseInt(dArray[2], 10); // Make sure all the values are numbers if (isNaN(mVal) || isNaN(dVal) || isNaN(yVal)){ // invalid date alert("Must enter a valid date. (mm/dd/yyyy)"); oDateVal.value=""; oDateVal.focus(); return false; } // Check day value if (dVal > 31 || dVal < 1){ // invalid day value alert("Must enter a valid date. (mm/dd/yyyy)"); oDateVal.value=""; oDateVal.focus(); return false; } // Check month value if (mVal > 12 || mVal < 1){ // invalid month value alert("Must enter a valid date. (mm/dd/yyyy)"); oDateVal.value=""; oDateVal.focus(); return false; } // Check year value if (yVal > 2049 || yVal < 1900){ if (yVal < 50 && yVal >= 0){ yVal="20"+leadingZero(yVal); oDateVal.value=leadingZero(mVal)+sSeparator+leadingZero(dVal)+sSeparator+yVal; } else if (yVal >= 50 && yVal < 100){ yVal="19"+yVal; oDateVal.value=leadingZero(mVal)+sSeparator+leadingZero(dVal)+sSeparator+yVal; } else { // invalid year value alert("Must enter a valid date. (mm/dd/yyyy)"); oDateVal.value=""; oDateVal.focus(); return false; } } return true; } function leadingZero(iVal){ if (iVal < 10){ iVal="0"+iVal; return iVal; } return iVal; } function dSplit(dateval, sepval){ var pos1; var pos2; var dArray; var foobar; foobar = new Array(0); dArray = new Array(3); // Get first separator position pos1 = dateval.indexOf(sepval, 0); // If it's the last char, it's bad if (pos1 == dateval.length - 1) return foobar; // Get next separator position if (pos1 != -1) pos2 = dateval.indexOf(sepval, pos1 + 1); else return foobar; if (pos2 == dateval.length - 1) return foobar; // Assign values into array if (pos2 != -1){ dArray[0] = dateval.substring(0, pos1); dArray[1] = dateval.substring(pos1 + 1,pos2); dArray[2] = dateval.substring(pos2 + 1,dateval.length + 1); } else { return foobar; } return dArray; }

Mail To: info@3pc.com