// This function validate a date with the following format // Day/Month/Year with: // Day 1-31 (optional zero on single digits) // Month 1-12 (optional zero on single digits) // Year One, Two or four digits // // It checks if the format is correct. // If the format is correct, it also checks for the the date existence // For example: 29/02/2007 does not exist // // @param dateValue A date in string format // @return validity of the date // @retvalue true date is valid // @retvalue false date is invalid function isDateValid(dateValue) { // Default result is true var result = true; var dateStr = dateValue.trim(); // Empty date field is correct if (dateStr.length > 0) { // This regular expression validate the input date format // to the following rules; // Day 1-31 (optional zero on single digits) // Month 1-12 (optional zero on single digits) // Year One, Two or four digits // // Or empty field // // Each date component is captured using the parenthesis. See matcher below var dateRegEx = new RegExp("^(0?[1-9]|[1-2][0-9]|3[0-1])/(0?[1-9]|1[0-2])/([0-9]{1,2}|[0-9]{4})$"); var matcher = dateRegEx.exec(dateStr); if (matcher != null) { // The date format is correct... // Check that the date is itself correct (for example 29/02/2007 does not exist) var day = matcher[1]; var month = matcher[2]; var year = matcher[3]; // If the year is one or two digits then the routine assumes a // year belongs in the 21st Century. // 0 --> 2000, 1 --> 2001... if (year < 100) { year += 2000; } // Build a date for validation using the internal native code var date = new Date(year, month-1, day); // Check that the stored date is the one we entered // otherwise, the date was incorrect if (date.getDate() != day || date.getMonth() != month-1 || date.getFullYear() != year) { result = false; } } else { result = false; } } return result; }