Solved

Validating consecutive input fields results in endless loop of alerts

Posted on 2004-08-11
12
543 Views
Last Modified: 2012-06-27
Hi,

I have a form that has consecutive input fields for phone numbers.  The script that validates the phone numbers checks to see if the phone number is correctly entered and if not, sends an alert box and points the focus back to the field.

The problem is that alert boxes seem to be getting activated in both fields and you can't exit out from the alert box.  You end up having to kill the browser and start over.  When I removed the focus, the issue goes away.  If you run the below code as is, you should see the problem.

Any help would be greatly appreciated.

Thanks,
Blue44

Here's my code:

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
<title>Untitled Document</title>


<script language="JavaScript" type="text/JavaScript">
function PhoneValidate(program, field)
{
    var x = null;
    eval("x=document."+program+"."+field+".value");
    if (x == "")
        {
      alert("Phone number must be entered as 619 555-1234.");
      eval("document.forms[\""+program+"\"]."+field+".focus()");
      return false;
        }
            
     var phoneregexp=/^\d\d\d\s?\d\d\d\-\d\d\d\d$/;
      
     if(x.length>0)
       {
                var match=x.match(phoneregexp);
      if (match)
      {
            return true;
       }
      else
           {
                 alert("Phone number must be entered as 619 555-1234.");
                 eval("document.forms[\""+program+"\"]."+field+".focus()");
                           return false;
           }
           return true;
       }
      }
</script>

</head>

<body>

<form action="ApplyHandler.htm" method="post" name="ApplyUpdate" >

Home Phone:
<input onBlur="PhoneValidate('ApplyUpdate', 'HomePhone')"      name="HomePhone" type="text" size="16" maxlength = "25">

<br>

Work Phone:                                                
<input onBlur="PhoneValidate('ApplyUpdate', 'WorkPhone')" name="WorkPhone" type="text" size="16" maxlength = "25">

<br>

Cell Phone:
<input onBlur="PhoneValidate('ApplyUpdate', 'CellPhone')" name="CellPhone" type="text" size="16" maxlength = "25">

<br>

Other Phone:
<input onBlur="PhoneValidate('ApplyUpdate', 'OtherPhone')" name="OtherPhone" type="text" size="16" maxlength = "25">

<br>

<input name="Submit" type="submit">

</form>



</body>
</html>
0
Comment
Question by:blue44
  • 3
  • 3
  • 2
  • +2
12 Comments
 
LVL 36

Expert Comment

by:Zyloch
Comment Utility
Hi

Change onBlur to onChange.


Regards,
Zyloch
0
 

Author Comment

by:blue44
Comment Utility
Zyloch,

Hello again.

I did that but the result is that it no longer validates or prompts an alert box at all.

Thanks,
Darius
0
 
LVL 5

Expert Comment

by:ho_alan
Comment Utility
hi there, u may try to use onChange as Zyloch said, :-)

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
<title>Untitled Document</title>


<script language="JavaScript" type="text/JavaScript">
function PhoneValidate(program, field)
{
   var x = null;
   eval("x=document."+program+"."+field+".value");
   if (x == "")
        {
    alert("Phone number must be entered as 619 555-1234.");
    eval("document.forms[\""+program+"\"]."+field+".focus()");
    return false;
       }
         
    var phoneregexp=/^\d\d\d\s?\d\d\d\-\d\d\d\d$/;
     
    if(x.length>0)
      {
               var match=x.match(phoneregexp);
    if (match)
     {
           return true;
     }
    else
         {
               alert("Phone number must be entered as 619 555-1234.");
               eval("document.forms[\""+program+"\"]."+field+".focus()");
                          return false;
         }
         return true;
     }
     }
</script>

</head>

<body>

<form action="ApplyHandler.htm" method="post" name="ApplyUpdate" >

Home Phone:
<input onChange="PhoneValidate('ApplyUpdate', 'HomePhone')"     name="HomePhone" type="text" size="16" maxlength = "25">

<br>

Work Phone:                                        
<input onChange="PhoneValidate('ApplyUpdate', 'WorkPhone')" name="WorkPhone" type="text" size="16" maxlength = "25">

<br>

Cell Phone:
<input onChange="PhoneValidate('ApplyUpdate', 'CellPhone')" name="CellPhone" type="text" size="16" maxlength = "25">

<br>

Other Phone:
<input onChange="PhoneValidate('ApplyUpdate', 'OtherPhone')" name="OtherPhone" type="text" size="16" maxlength = "25">

<br>

<input name="Submit" type="submit">

</form>


</body>
</html>
0
 
LVL 5

Expert Comment

by:ho_alan
Comment Utility
because if u use "onBlur", whenever u out-focus the field, your alert box will be prompted, u can't move to another field
0
 
LVL 36

Expert Comment

by:Zyloch
Comment Utility
Using onchange, your code should validate. You have to change something in the input field, then blur it by clicking elsewhere. If you want it whenever a key is pressed, use onkeypress instead.
0
 
LVL 14

Accepted Solution

by:
ziffgone earned 150 total points
Comment Utility
No fellas, I tried the onChange too, but things wouldn't validate as, just as blue44, said.

Hi blue44, here is what I came up with:

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
<title>Untitled Document</title>

<script type="text/JavaScript">
var theNums = new Array('HomePhone','WorkPhone','CellPhone','OtherPhone');
var theList = new Array();
var good = 0;
function checkAllFieldsEmpty(theFrm){
       theList = theFrm.getElementsByTagName('input');
    for(b=0;b<theNums.length;b++){
       for(i=0;i<theList.length;i++){
          if(theList[i].name == theNums[b]){
              if(theList[i].value.length < 1){
                   not_valid(theList[i]);
                   return false;
              }
              else{                
                 good++
              }
          }
       }
     }
     if(good == 4){
         theFrm.submit();
     }
}
       
function checkLength(cfield){
       if(cfield.value != ""){
         if(cfield.value.length != 12){
             not_valid(cfield);
         }
         else{
             return;
         }
     }
     else{
        return;
     }
}
function not_valid(nfield){
          good = 0;
          alert("Phone number must be entered as 619 555-1234.");
          nfield.select();
          nfield.focus();
}
function PhoneValidate(field){
   if(field.value != ""){
    if(field.value.length > 11){
      var phoneregexp=/^\d\d\d\s?\d\d\d\-\d\d\d\d$/;
         if(field.value.match(phoneregexp)){
           return true;
         }
         else{
           not_valid(field);
           return false;
         }
     }
     else{
         return true;
     }
  }
  else{
     return true;
  }
}
</script>
</head>
<body>
<form name="PhoneNumbers" action="ApplyHandler.htm" method="post" name="ApplyUpdate" onsubmit="checkAllFieldsEmpty(this);return false;">
Home Phone:
<input onKeyup="PhoneValidate(this);" onBlur="checkLength(this);" name="HomePhone" type="text" size="16" maxlength = "25"><br>
Work Phone:                                        
<input onKeyup="PhoneValidate(this);" onBlur="checkLength(this);" name="WorkPhone" type="text" size="16" maxlength = "25"><br>
Cell Phone:
<input onKeyup="PhoneValidate(this);" onBlur="checkLength(this);" name="CellPhone" type="text" size="16" maxlength = "25"><br>
Other Phone:
<input onKeyup="PhoneValidate(this);" onBlur="checkLength(this);" name="OtherPhone" type="text" size="16" maxlength = "25"><br>
<input name="Submit" type="submit">
</form>
</body>
</html>

I think I managed to cover all eventualities.

Note: it only checks to see if any of the fields are empty when the form is submitted.

Regards...
0
Top 6 Sources for Identifying Threat Actor TTPs

Understanding your enemy is essential. These six sources will help you identify the most popular threat actor tactics, techniques, and procedures (TTPs).

 
LVL 36

Expert Comment

by:Zyloch
Comment Utility
Hmm... That's odd, ziff--any ideas why?
0
 
LVL 33

Assisted Solution

by:sajuks
sajuks earned 100 total points
Comment Utility
Try this
<html>
<head>
<title>Untitled Document</title>


<script language="JavaScript" type="text/JavaScript">
function PhoneValidate(program, field)
{
    var x = null;
    eval("x=document."+program+"."+field+".value");
    if (x == "")
        {
     eval("document.forms[\""+program+"\"]."+field+".focus()");
          alert("Phone number must be entered as 619 555-1234.");
     return false;
        }
         
     var phoneregexp=/^\d\d\d\s?\d\d\d\-\d\d\d\d$/;
     
     if(x.length>0)
       {
                var match=x.match(phoneregexp);
     if (match)
     {
           return true;
      }
     else
          {
                eval("document.forms[\""+program+"\"]."+field+".focus()");
                                alert("Phone number must be entered as 619 555-1234.");
                           return false;

          }
          return true;
      }
      }
</script>

</head>

<body>

<form action="ApplyHandler.htm" method="post" name="ApplyUpdate" >

Home Phone:
<input onchange="return PhoneValidate('ApplyUpdate', 'HomePhone')"     name="HomePhone" type="text" size="16" maxlength = "25">

<br>

Work Phone:                                        
<input onchange="return  PhoneValidate('ApplyUpdate', 'WorkPhone')" name="WorkPhone" type="text" size="16" maxlength = "25">

<br>

Cell Phone:
<input onchange="return  PhoneValidate('ApplyUpdate', 'CellPhone')" name="CellPhone" type="text" size="16" maxlength = "25">

<br>

Other Phone:
<input onchange="return PhoneValidate('ApplyUpdate', 'OtherPhone')" name="OtherPhone" type="text" size="16" maxlength = "25">

<br>

<input name="Submit" type="submit">

</form>



</body>
</html>
0
 
LVL 33

Expert Comment

by:sajuks
Comment Utility
alert should be after eval
0
 

Author Comment

by:blue44
Comment Utility
Thanks to all!

Ziffgone & sajuks solutions do validate the phone numbers and the alert boxes display correctly, however, one can tab off these boxes without entering anything and there's no prompt.  Can you add to your code for this functionality? I think we've got a solution then!!
0
 
LVL 14

Expert Comment

by:ziffgone
Comment Utility
Hi blue44, with my code, it deliberately lets the user tab off without inputing anything.

The reason behind this is as the only way to check if nothing was typed is by using the onBlur event, and this is where the problem was. As soon as you tabbed off of a field, it blurred and placed the focus back on the previous field, which in turn caused the one they were just on to blur without having typed anything there yet. As soon as the new field loses focus, the script tried to refocus on it, causing field 1 to blur again, etc., creating the endless loop which hung the browser.

So, with my code, I allow the user to tab off of the field without typing anything, it's the only way to go. If they have typed something, but it isn't the proper phone number format, it alerts them and re-focuses on the error field. I do allow them to tab off without typing anything though. But to cover this, I added the -onsubmit="checkAllFieldsEmpty(theFrm);return false;"- function:

<form name="PhoneNumbers" action="ApplyHandler.htm" method="post" name="ApplyUpdate" onsubmit="checkAllFieldsEmpty(this);return false;">

This function checks all fields before submitting the form. If the "checkAllFieldsEmpty(theFrm)" function finds any empty fields, it disallows submission and focuses on the empty field.

I threw about many ideas on how to disallow tabbing to the next field when blank, including seeing if a keycode based event would work, but, alas, I don't know what keycode the tab key is, nor if it actually has one. I have a script that returns the keycode of any key pressed, but some keys aren't registered, the tab key, print screen key, control key and the alt key to name a few.

Anyway, if your add the onsubmit function it will not allow any blank fields to be submitted.

It also only checks the text fields you want, so if you have more text fields other than the phone number fields, it will ignore those text fields so you don't get an alert when someone enters anything into a different text field than the phone number fields. This is set up in the "theNums" Array at the top of the script. If you have another field to check, simply add the name of the field to that array.

That's about it in a nutshell, hope my explaination makes sense.

Regards....
0
 

Author Comment

by:blue44
Comment Utility
Thanks, ziffgone.  I get it now.  I'll make the necessary adjustments to my script.

Best regards,
blue44
0

Featured Post

IT, Stop Being Called Into Every Meeting

Highfive is so simple that setting up every meeting room takes just minutes and every employee will be able to start or join a call from any room with ease. Never be called into a meeting just to get it started again. This is how video conferencing should work!

Join & Write a Comment

Suggested Solutions

Article by: DanRollins
This article describes a JavaScript program that creates a maze made of hexagonal cells.  In Part 2 (http://www.experts-exchange.com/Programming/Languages/Scripting/JavaScript/A_7850-Hex-Maze-Part-2.html), we'll extend the program by adding a depth-…
International Data Corporation (IDC) prognosticates that before the current the year gets over disbursing on IT framework products to be sent in cloud environs will be $37.1B.
The viewer will learn the basics of jQuery, including how to invoke it on a web page. Reference your jQuery libraries: (CODE) Include your new external js/jQuery file: (CODE) Write your first lines of code to setup your site for jQuery.: (CODE)
The viewer will learn the basics of jQuery including how to code hide show and toggles. Reference your jQuery libraries: (CODE) Include your new external js/jQuery file: (CODE) Write your first lines of code to setup your site for jQuery…

728 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

9 Experts available now in Live!

Get 1:1 Help Now