earwig75
asked on
JavaScript date form validation
I am using the below script to validate a couple fields and using regular expressions for the validation. The first one (retheFormat) works fine, but the date check never seems to even kick off. The date field name is "cancelDate". Can someone have a look and see if you can figure out what I'm doing wrong?
<script language="javascript" type="text/javascript">
var rethefFormat = /\d\d\d\d-\d\d-\d\d\/(.*)?/;
var reDateFormat = /^(\d{1,2})\/(\d{1,2})\/(\d{4})$/;
var frmvalidator = new Validator("frmProjectX");
frmvalidator.addValidation("thefincidNumber","req","thef incid Number is a required field.");
frmvalidator.setAddnlValidationFunction(DoCustomValidation);
function DoCustomValidation()
{
var frm = document.forms["frmProjectX"];
var valuethef = document.getElementsByName("thefincidNumber")[0].value;
if(valuethef.search (rethefFormat) == -1)
{
sfm_show_error_msg('thef incid Number must be in thef Format YYYY-MM-DD/XXXXX',frm.incidNumber);
return false;
}
else
{
return true;
}
//check date format
if(frm.cancelDate.value != '') {
if(regs = frm.cancelDate.value.match(reDateFormat)) {
// day value between 1 and 31
if(regs[1] < 1 || regs[1] > 31) {
alert("Invalid value for day: " + regs[1]);
frm.cancelDate.focus();
return false;
}
// month value between 1 and 12
if(regs[2] < 1 || regs[2] > 12) {
alert("Invalid value for month: " + regs[2]);
frm.cancelDate.focus();
return false;
}
// year value between 1902 and 2016
if(regs[3] < 1902 || regs[3] > (new Date()).getFullYear()) {
alert("Invalid value for year: " + regs[3] + " - must be between 1902 and " + (new Date()).getFullYear());
frm.cancelDate.focus();
return false;
}
} else {
alert("Invalid date format: " + frm.cancelDate.value);
frm.cancelDate.focus();
return false;
}
}
alert("Date field has been validated!");
return true;
}
</script>
ASKER
@EddieShipman, the problem isn't the regular expression, the script isn't even checking the field for some reason. It will submit no matter what is entered in the date field.
ASKER CERTIFIED SOLUTION
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Your regex would allow months like 21 or days like 65.
This date validates using your string:
This date validates using your string:
21/65/9978
ASKER
Removing the else from the first regular expression validation allows the script to continue to the date validation.
Ok, if you want to allow invalid dates, that is fine with me...
Open in new window
This one does MM/DD/YYYY