Submit form problem when textfield onBlur validation

Hi

I have a number of forms where I validate for example a number of textfields when an action triggers the onBlur event on a textfield. The problem occurs when I change something in the textfield and then hit the submit-button. Then the thing up in the right corner that rotates while the page is loading never stops. It's like a JavaScript function loops or something but that is not the problem. The problem seems to be that when I hit the submit button and some JavaScript is triggered by the onBlur event on the textfield and the onSubmit function on the form. It all ****s up.
In a page I can have from 1 to about 100 textfields.
I'm running Windows XP Pro with all the latest updates and so. I have mySQL and PHP installed on the server.

MY QUESTION: How do I solve this AND can I optimize the functions below in some way.

Here are som code so you should understand it better.

TEXTFIELD
------------
<input name="field1" type="text" id="field1" onBlur="isText(this, 'text', '1')">
<img src="../images/icons/16_empty.gif" name="a_kategori_namnSW" width="16" height="16" id="a_kategori_namnSW">

JavaScript
-----------
function isText(obj, name, required) {
      var imageName = obj.name + "SW";
      var errMsg = "";
      var value = obj.value;
      
      // If the field is required
      if(required == 1)
            if (value == "")
                  errMsg += "You have forgot to fill in" + name + "\n"
      
      // If there is any false chars in the field
      var iChars = "|,\":<>[]{}`\';&$#";
      for (var i = 0; i < value.length; i++) {
            if (iChars.indexOf(value.charAt(i)) != -1)
                   errMsg += name + " has the illegal character " + value.charAt(i) + "\n";
         }

      // change the validate image to correct or false
      setValidateImage(obj, errMsg);
      
      // return the error message
      return errMsg;
}
function validate(type){
      missing = "";

      with(document.f1){
            missing += isText(text, 'Name of field', '1')      
                } // end with
      if(type == 1){
            if(missing == "")
                  return true
            else
            {
                  alert("Error message:\n************************************\n" +missing )
                  return false
            }
      }
}
function setValidateImage(obj, errMsg){
      var imageName = obj.name + "SW";
      // if errMsg = "" then the field is valid, otherwise somethings is wrong
      if(errMsg == ""){
            // let the user see that the field is correct
            PP_swapImage(imageName,'','../images/icons/16_correct.gif',1);
      }
      else{
            // let the user see that the field is false
            PP_swapImage(imageName,'','../images/icons/16_false.gif',1);
      }
}

// THIS TWO FUNCTIONS BELOW IS DREAMWEAVER STANDARD FUNCTIONS SO THIS IS PROBABLY NOT WHERE THE PROBLEM IS
function PP_findObj(n, d) { //v4.01
  var p,i,x;  if(!d) d=document; if((p=n.indexOf("?"))>0&&parent.frames.length) {
    d=parent.frames[n.substring(p+1)].document; n=n.substring(0,p);}
  if(!(x=d[n])&&d.all) x=d.all[n]; for (i=0;!x&&i<d.forms.length;i++) x=d.forms[i][n];
  for(i=0;!x&&d.layers&&i<d.layers.length;i++) x=PP_findObj(n,d.layers[i].document);
  if(!x && d.getElementById) x=d.getElementById(n); return x;
}
function PP_swapImage() { //v3.0
  var i,j=0,x,a=PP_swapImage.arguments; document.MM_sr=new Array; for(i=0;i<(a.length-2);i+=3)
   if ((x=PP_findObj(a[i]))!=null){document.MM_sr[j++]=x; if(!x.oSrc) x.oSrc=x.src; x.src=a[i+2];}
}

FORM
------
<form action="admArtikel02.php" method="post" name="f1" id="f1" onSubmit="return validate('1')">

//Thomas
tombombadilllAsked:
Who is Participating?

[Product update] Infrastructure Analysis Tool is now available with Business Accounts.Learn More

x
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

OMC2000Commented:
set form action value to some dummy js function that does nothing. When text field is valid re-assign its value to proper php script.
YOu could make dummy function assignement on focus for that text box
tombombadilllAuthor Commented:
I don't really understand I think.

Do you mean that I should move all my validation to PHP?
That would require too much job so that is not possible.
gam3r_3xtr3m3Commented:
considering, people with active scripting disabled would not have their form validated by your script. which you also need server side scripting. well, what do you need to validate in your script? i cant seem to understand without the whole code.
Determine the Perfect Price for Your IT Services

Do you wonder if your IT business is truly profitable or if you should raise your prices? Learn how to calculate your overhead burden with our free interactive tool and use it to determine the right price for your IT services. Download your free eBook now!

tombombadilllAuthor Commented:
This is for an application that is run in IE5.5 or later and will have active scripting activated so that is not a problem. In some cases I use server side scripting for validation too but most of the times I will use JavaScript for this part.

The code above should be enough for you to help me if you can help me I think. I've included the parts where the problem lies.

Q1: Can you solve the Submit and onBlur problem?

Q2: Can you in some way optimize the code for validation and do it in some other way?



OMC2000Commented:
function validate(type){
     missing = "";

     with(document.f1){
          missing += isText(text, 'Name of field', '1')    
                } // end with
     if(type == 1){
          if(missing == "")
               f1.action = "admArtikel02.php";
               return true
          else
          {
               alert("Error message:\n************************************\n" +missing )
               return false
          }
     }
}
function setValidateImage(obj, errMsg){
     var imageName = obj.name + "SW";
     // if errMsg = "" then the field is valid, otherwise somethings is wrong
     if(errMsg == ""){
          // let the user see that the field is correct
          PP_swapImage(imageName,'','../images/icons/16_correct.gif',1);
     }
     else{
          // let the user see that the field is false
          PP_swapImage(imageName,'','../images/icons/16_false.gif',1);
     }
}

// THIS TWO FUNCTIONS BELOW IS DREAMWEAVER STANDARD FUNCTIONS SO THIS IS PROBABLY NOT WHERE THE PROBLEM IS
function PP_findObj(n, d) { //v4.01
  var p,i,x;  if(!d) d=document; if((p=n.indexOf("?"))>0&&parent.frames.length) {
    d=parent.frames[n.substring(p+1)].document; n=n.substring(0,p);}
  if(!(x=d[n])&&d.all) x=d.all[n]; for (i=0;!x&&i<d.forms.length;i++) x=d.forms[i][n];
  for(i=0;!x&&d.layers&&i<d.layers.length;i++) x=PP_findObj(n,d.layers[i].document);
  if(!x && d.getElementById) x=d.getElementById(n); return x;
}
function PP_swapImage() { //v3.0
  var i,j=0,x,a=PP_swapImage.arguments; document.MM_sr=new Array; for(i=0;i<(a.length-2);i+=3)
   if ((x=PP_findObj(a[i]))!=null){document.MM_sr[j++]=x; if(!x.oSrc) x.oSrc=x.src; x.src=a[i+2];}
}

FORM
------
<form action="javascript:0" method="post" name="f1" id="f1" onSubmit="return validate('1')">

gam3r_3xtr3m3Commented:
i can optimize it... just tell me what you need to validate and how you'd validate it.
tombombadilllAuthor Commented:
Guide to the code:

The code work as follows. When you have entered something in the textfield and click somewhere outside the box it triggers the event onBlur. On that event the textfield calls for the function isText() that validates the textfield. If its right it swaps an image to show the user that it's right. If it's wrong it shows another image. The function also returns a string that contains the error message for that field.

When you have completed the whole form you hit the submit button. This triggers the event onSubmit on the form which calls for the function validate that validates all the textfields in the form and if something is wrong it alert a error message. validate(0) checks the whole form without submitting it and validate(1) does the same but this time it submits the form.

The problem occurs when you hit the submit button after you have typed in the textfield and hit the submit button.
I hope this helps you all in helping me. =)
tombombadilllAuthor Commented:
ok...here is what I need to optimize if possible
Why I replace a , with a . is because here in sweden we use that as a decimal sign. 2,33 Swedeish == 2.33 English

function isNumber(obj, name, required, minimum, maximum, maxfracs) {
      // set up the different objectvariables
      var errMsg = "";
      var value = obj.value;
      
      // set up the error message if the field is empty
      if(required == 1 && value == ""){
            errMsg += "Fyll i fältet " + name + "\n";
      }
      else{
            // Validate that the value is a number
            value = value.replace(",",".");
            if(isNaN(value))
                  errMsg += "Field " + name + " is not a number\n";

            // Validate that the value is in range (minimum <= value <= maximum)
            if(value < minimum || value > maximum){
                  errMsg += "Field " + name + " should be a number in eange "+minimum+" and " +maximum+ "\n";
            }

            // Validate number of maximum decimals and some decimals specific things
            if(value.indexOf(".") != -1){
                  valueFrac = value.substr(value.indexOf(".")+1);
                  if(valueFrac.length > maxfracs)
                        errMsg += "Field" + name + " can only hold two "+ maxfracs +" decimals\n";
                  if(value.indexOf(".") == 0)
                        errMsg += name + " can't start with a decimal sign\n";
                  if(value.indexOf(".") == value.length -1)
                        errMsg += name + " can't end with a decimal sign\n";
            }
      }

      // return the error message
      return errMsg;
}
James RodgersWeb Applications DeveloperCommented:
the problem is the onBlur event, don't use onblur to validate, when you try to click on the button the onblur event fires and the button loses focus so is not clicked, use the onKeyUp event inplace of the onblur or ideally have

<form onSubmit="return validateRoutine(this)">

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
tombombadilllAuthor Commented:
ok...so that's why sometimes you click submit and nothing really happens. But if I have like 1-100 textfield and would like to show the user the moment he type it in how do I do then.

The typical user type a value in a textbox and then hit the TAB button on the keyboard or hit the mousebutton somewhere on the page.
Is there any good way of of doing the validation rigtht away. Is it best to use onKeyUp then?

jaysolomonCommented:
Why not just use a loop (for) and then validate onsubmit

here is an example, you can modify it

This should work

<html>
<head>
<title></title>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
<script type="text/javascript">
<!--
function validate(fObj){
var err = "";
//var required = document.getAttribute("required");
      for(i=0; i<fObj.length; i++){
            var e = fObj.elements[i];
            if(e.type == "text" || e.type == "textarea" || e.type == "password"){
                  if(e.getAttribute("required")== 1){
                  if(e.value == ""){
                        err += "- "+ e.name;
                  }
            }
            }
            if(err != ""){
                  alert("The following fields contain errors\n\n"+ err);
                        return false;
            }
      return true;
      }
}
// -->
</script>
</head>
<body>
<form name="form1" method="post" action="" onsubmit="return validate(this);">
      <input type="text" name="txt1" required="1">
      <input type="text" name="txt2" required="0">
      <input type="text" name="txt3" required="1">
      <input type="submit" name="Submit" value="Submit">
</form>
</body>
</html>
James RodgersWeb Applications DeveloperCommented:
use onkeyup
onKeyUp="isNumber(...) " although this can be anoying if the user can't type and keeps hitting the wrong key


or wait until the user submits the form then validate all the data at once

<script>
function validateRoutine(objForm){

if(isNaN(objForm.textBox.value)){  //textbox means the actual name of the textbox to validate
   alert("invalid")
   return false;
}
... do for all input boxes as necessary
}
</script>
James RodgersWeb Applications DeveloperCommented:
thanks for the points
tombombadilllAuthor Commented:
You are welcome... =)

Thanks for the help. Have got a few new ideas about solving the whole validation process from you and the others who recieved points.
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
Web Languages and Standards

From novice to tech pro — start learning today.