May. 16, 2004, 06:58 PM
I've got a simple form:
I've written some JavaScript that used for field level validation:
The problem is : If one enters data that turns out to be invalid when using the TAB key or using the mouse-click on the next field which also fires onBlur() this causes the ALERT to fire in an endless loop. The objective is -- if the field data is not valid then focus must return to the element that contains the error to enable the user to correct.
Anyone have the solution that fixes my code?
Thanks.
Code:
<html xmlns="http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<head>
<title>Phone and E-mail</title>
<script type="text/javascript" src='validtest.js'></script>
</head>
<body>
<FORM name="servform" onsubmit="return checkform();" method="post">
<table cellpadding=0 cellspacing=5 border=0><tr>
<td align="left">Your E-mail:</td><td align="left">
<input type="text" value="" name="email" onBlur="checkemail(this.value)" /></td>
</tr><tr>
<td align="left">Your Phone Number:</td><td align="left">
<input type="text" value="" name="cust_phone" onBlur="checkPhone(this.value)" /></td>
</tr>
<tr>
<td>
<input type="submit" value="Send" />
</td>
</tr>
</table>
</form>
</body>
</html>
I've written some JavaScript that used for field level validation:
Code:
// validtest.js
function checkform() {
var msgtext="";
if (document.servform.email.value == "") {
msgtext = msgtext + "Required! E-mail Address: field is empty\n";
}
if (document.servform.cust_phone.value == "") {
msgtext = msgtext + "Required! Phone Number: field is empty\n";
}
if(msgtext != "") {
alert(msgtext);
return false;
}
return true;
}
// E-mail
function checkemail(yourEmail){
if(yourEmail.match(/^.[^<>@]+\@(\[?)[a-zA-Z0-9\-\.]+\.([a-zA-Z]{2,3}|[0-9]{1,3})(\]?)$/)){
return true;
} else {
alert("Enter a valid E-mail Address.\n example: [email protected]");
document.servform.email.select();
document.servform.email.focus();
return false;
}
}
// phone number
function checkPhone(cust_phone){
if(cust_phone.match(/^\(?\d{3}\)?\s|-\d{3}-\d{4}$/)) {
return true;
} else {
alert("Enter a valid Phone Number: \n example: ###-###-####");
document.servform.cust_phone.select();
document.servform.cust_phone.focus();
return false;
}
}
The problem is : If one enters data that turns out to be invalid when using the TAB key or using the mouse-click on the next field which also fires onBlur() this causes the ALERT to fire in an endless loop. The objective is -- if the field data is not valid then focus must return to the element that contains the error to enable the user to correct.
Anyone have the solution that fixes my code?
Thanks.