regexp date validation issue with correcting invalid dates
I'm trying to use regular expressions to validate dates entered via multiple select boxes.
The regexp I'm using (from http://www.regexplib.com ) is successfully detecting invalid dates brilliantly. The issue I'm having is that date validation continues to fail on subsequent submissions, even when the date has been corrected to be valid.
Altering the 'day' field to be a value less than ten produces the expected behavior (passes validation).
I've put together a small test page that replicates the problem behavior.
Test case:
* Submit the form with Feb. 31 (any year or time) - alert will appear and form won't be submitted
* Alter the 'day' field to 24 - alert will appear and form won't be submitted
* Alter the 'day' field to 8 - alert will not appear and form will be submitted
//<![CDATA[
function validDate(month, day, year) {
var mmddyyyy = month + '/' + day + '/' + year;
// alert(mmddyyyy);
return (mmddyyyy.match(/^(((0[1-9]|[12]\d|3[01])\/(0[13578]|1[02])\/((1[6-9]|[2-9]\d)\d{2}))|((0[1-9]|[12]\d|30)\/(0[13456789]|1[012])\/((1[6-9]|[2-9]\d)\d{2}))|((0[1-9]|1\d|2[0-8])\/02\/((1[6-9]|[2-9]\d)\d{2}))|(29\/02\/((1[6-9]|[2-9]\d)(0[48]|[2468][048]|[13579][26])|((16|[2468][048]|[3579][26])00))))$/)) ? true : false;
}
function validate(myForm) {
var dateFields = myForm.date_fields.value.split("|");
var errorString = '';
var errorDate = '';
//Validate those dates
for (var i=0; i < dateFields.length; i++) {
var dateparts = dateFields[i].split(",");
var month = document.getElementById(dateparts[0]);
var day = document.getElementById(dateparts[1])
var year = document.getElementById(dateparts[2]);
var month = month.options[month.selectedIndex].value;
var day = day.options[day.selectedIndex].value;
var year = year.options[year.selectedIndex].value;
var title = dateparts[3] + " had an invalid date.";
// var invalidDate = false;
if (!validDate(month,day,year)) {
// alert(month + day + year + " failed.");
errorDate += title + "\n";
}
}
if (errorString != '' || errorDate != '') {
errorString = errorString.slice(0,errorString.length-2);
errorDate = errorDate.slice(0,errorDate.length-2);
window.alert("Please fill in the following required fields before submitting this form:\n\n"+errorString+"\n\n"+errorDate)
return false;
} else {
return true;
}
}
Re: regexp date validation issue with correcting invalid dates
Originally posted by dimmerswitch var mmddyyyy = month + '/' + day + '/' + year;
Rather than combining the three components into one string then trying to validate, you should validate each of the 3 parts separately. This would make what you're trying to do much easier. But, if you're happy with what you've got, that works too I guess...
The Web Standards Project – Build accessible standard compliant websites, please! Browse Happy – Don't forget to support the browsers with standard compliance
Bookmarks