function checkDate(fld) { var mo, day, yr; var entry = fld.value; var re = /\b\d{1,2}[\/-]\d{1,2}[\/-]\d{4}\b/; if (re.test(entry)) { var delimChar = (entry.indexOf("/") != -1) ? "/" : "-"; var delim1 = entry.indexOf(delimChar); var delim2 = entry.lastIndexOf(delimChar); mo = parseInt(entry.substring(0, delim1), 10); day = parseInt(entry.substring(delim1+1, delim2), 10); yr = parseInt(entry.substring(delim2+1), 10); var testDate = new Date(yr, mo-1, day); if (testDate.getDate( ) == day) { if (testDate.getMonth( ) + 1 == mo) { if (testDate.getFullYear( ) == yr) { return true; } else { alert("There is a problem with the year entry."); } } else { alert("There is a problem with the month entry."); } } else { alert("There is a problem with the date entry."); } } else { alert("Incorrect date format. Enter as mm/dd/yyyy."); } return false; }
The checkDate( ) validation function in Example 2-3 assumes that users will enter dates in either mm/dd/yyyy or mm-dd-yyyy formats (in that order only), and that the validation must test for the entry of a true date. There is no boundary checking here, so practically any year is accepted. As a form-validation function, this one takes a ref- erence to the text input element as the sole argument. Upon successful validation, the function returns true; otherwise, the user receives an alert message with some level of detail about the error, and the function returns false.

Be the first to comment

You can use [html][/html], [css][/css], [php][/php] and more to embed the code. Urls are automatically hyperlinked. Line breaks and paragraphs are automatically generated.