PDA

View Full Version : multiple date validation events in form


wam
01-25-2008, 07:33 PM
Hi I'm a newbie and have searched the forums for help with using an event twice or more on a page but am not getting it. Can someone provide some code sample to help me in the right direction. I'm using the date validate function and need to use it for 3 text input fields. I've tried renaming the function variable and copying the code twice, then using an onload event with the different names but all I got was stuck in a loop.

Here's the code:

<script type="text/javascript">
<!--
function validateDate(fld) {
var RegExPattern = /^(?=\d)(?:(?:(?:(?:(?:0?[13578]|1[02])(\/|-|\.)31)\1|(?:(?:0?[1,3-9]|1[0-2])(\/|-|\.)(?:29|30)\2))(?:(?:1[6-9]|[2-9]\d)?\d{2})|(?:0?2(\/|-|\.)29\3(?:(?:(?:1[6-9]|[2-9]\d)?(?:0[48]|[2468][048]|[13579][26])|(?:(?:16|[2468][048]|[3579][26])00))))|(?:(?:0?[1-9])|(?:1[0-2]))(\/|-|\.)(?:0?[1-9]|1\d|2[0-8])\4(?:(?:1[6-9]|[2-9]\d)?\d{2}))($|\ (?=\d)))?(((0?[1-9]|1[012])(:[0-5]\d){0,2}(\ [AP]M))|([01]\d|2[0-3])(:[0-5]\d){1,2})?$/;
var errorMessage = 'Please enter valid date as month, day, and four digit year.';
if ((fld.value.match(RegExPattern)) && (fld.value!='')) {
// alert('Date is OK');
} else {
alert(errorMessage);
fld.focus();
}
}

//-->
</script>

<!-- It works fine on one field but none of the modifications work for multiple. I removed the body onload event since it didn't work and here's the form: -->

<form name="getlist" action="nextpage.htm" method="POST">
<INPUT TYPE="text" NAME="requestdate" onblur="validateDate(this)">
<INPUT TYPE="text" NAME="approvaldate" onblur="validateDate(this)">
<INPUT TYPE="text" NAME="startdate" onblur="validateDate(this)">

<INPUT TYPE="submit" NAME="-find" VALUE="Start Search">
</form>

Kor
01-27-2008, 08:49 AM
it is a classical mistake of using the combination onblur/focus() upon the same element.
The loop is inevitable when bluring a textbox and focus the other. onblur starts the function, sees the error and focus again the first textbox. But, if focuses the first textbox it will also blur the second one, calling the function again and moving again the focus on the second textbox, but this will blur the first one which.... and so on, in an endless loop

One solution could be the using of the onchange event handler instead of onblur, because onchange will trigger the function only if both conditions are fulfilled:
1. if the element looses it's focus
2. if the element changes it's value since previously has been gaining the focus