Go Premium for a chance to win a PS4. Enter to Win

x
  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 1148
  • Last Modified:

Javascript validation...avoiding infinite loop

I have a several fields on a form and when I tab out of each field I use javascript to validate the field.  If there is an error then I set the focus back to that field.  Works great... unless...

-You tab out of FIELD1 without filling it in and you are brought to FIELD2.  
-The OnBlur event validates FIELD1 when you exit and discovers you have not typed a value so it puts you back in FIELD1.  
-When you are put back in FIELD1 the OnBlur event of FIELD2 is triggered and it discovers I haven't entered a value for FIELD2.  It then tries to put focus back on FIELD2.  

This is an infinite loop...

Is there an easy workaround to avoid this?
0
snocross
Asked:
snocross
  • 2
  • 2
1 Solution
 
bennyliawCommented:
Create a flag variable (could be a hidden field or just a simple javascript variable) that will be set true to indicate that you are validating a field. If the flag is turn on you should never validate another field.

So in your javascript validation code in onBlur event of the fields, you will need to check the flag:

if (!flag) {
   flag = true;
   // your validation goes here
   // if (field1 is wrong)
   //     set focus to field 1
   flag = false;
}

You need to initialized the flag to false upon loading the form

---benny
0
 
snocrossAuthor Commented:
I tried this and here's what happens;  it finds a validation error and prompts me to fix it.  Then when I fix the error and tab out of the field it doesn't recheck the validation ever again.  How can I reset the flag once the validation error has been fixed?
0
 
bennyliawCommented:
Sorry, I thought a boolean flag would work.

Here's the revision that has been tested, flag is now defined as the "field being validated".
In your validation script you will now check whether the current field is the one being validated. (Note you will need to initiazed the flag with "")

function checkField1() {
  if (flag == "Field1" | flag == "") {
    if (document.forms[0].Field1.value == "")
    {  
      alert("Please enter a value in Field1");
      flag = "Field1";
      document.forms[0].Field1.focus();
    }
    else
      flag = ""
  }
}

function checkField2() {
  if (flag == "Field2" | flag == "") {
    if (document.forms[0].Field2.value == "")
    {  
      alert("Please enter a value in Field2");
      flag = "Field2";
      document.forms[0].Field2.focus();
    }
    else
      flag = ""
  }
}

0
 
snocrossAuthor Commented:
Works great!  Thanks!
0

Featured Post

Ask an Anonymous Question!

Don't feel intimidated by what you don't know. Ask your question anonymously. It's easy! Learn more and upgrade.

  • 2
  • 2
Tackle projects and never again get stuck behind a technical roadblock.
Join Now