//Instant Validation with JavaScript-enabled WebDB //Listing 3 //The JavaScript function isCompleteDate checks whether the text entered in a field has //the date format MM/DD/YYYY and appropriate values for month/day/year, displaying an //error message and returning a value of “false” if it does not. function isCompleteDate(theElement, theName) { // This function checks if the text entered in a field // has the format MM/DD/YYYY. // It also checks if the days and months are valid and // if the year is 1500 or later var objectName = theName; //---- since we need the same functionality for errors ---- //---- we create a function to simplify error display ---- function showError(message) { alert(objectName + ": " + message); theElement.focus(); } var date_regex = /^(\d{1,2})\/(\d{1,2})\/(\d{4})$/; var date_str = theElement.value; // ^ indicates start of expression // \d{1,2} - the \d means digits and {1,2} means 1 or 2 digits // $ indicates end f expression if (!date_regex.test(date_str)) { showError(theElement.value + " is NOT a valid date"); theElement.focus(); return(false); } //---- separate the month, day and year ---- var month = RegExp.$1; var day = RegExp.$2; var year = RegExp.$3; if (year < 1500) { showError(year + " is not a valid year"); return(false); } if (month < 1 || month > 12) { showError(month + " is not a valid month"); return(false); } if (day == 0) { showError(day + " is not a valid day"); return(false); } if ((month == 1 || month == 3 || month == 5 || month == 7 || month == 8 || month == 10 || month == 12) && (day > 31)) { showError(day + " is not a valid day for month " + month); return (false) ; } if ((month == 4 || month == 6 || month == 9 || month == 11) && (day > 30)) { showError(day + " is not a valid day for month " + month); return(false); } if (month == 2) { //---- check for leap year ----- if ((day > 28) && (year%4 != 0)) { showError(day + " is not a valid day for month " + month + " of year " + year); return(false); } if ((day > 29) && (year%4 == 0)) { showError(day + " is not a valid day for month " + month + " of year " + year); return(false); } } return(true); }