Solved

Submit form problem when textfield onBlur validation

Posted on 2003-12-10
14
2,236 Views
Last Modified: 2013-11-18
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
0
Comment
Question by:tombombadilll
  • 6
  • 3
  • 2
  • +2
14 Comments
 
LVL 15

Expert Comment

by:OMC2000
ID: 9911100
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
0
 

Author Comment

by:tombombadilll
ID: 9911188
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.
0
 
LVL 7

Expert Comment

by:gam3r_3xtr3m3
ID: 9911427
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.
0
 

Author Comment

by:tombombadilll
ID: 9911518
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?



0
 
LVL 15

Assisted Solution

by:OMC2000
OMC2000 earned 100 total points
ID: 9911530
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')">

0
 
LVL 7

Expert Comment

by:gam3r_3xtr3m3
ID: 9911549
i can optimize it... just tell me what you need to validate and how you'd validate it.
0
 

Author Comment

by:tombombadilll
ID: 9911568
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. =)
0
Why You Should Analyze Threat Actor TTPs

After years of analyzing threat actor behavior, it’s become clear that at any given time there are specific tactics, techniques, and procedures (TTPs) that are particularly prevalent. By analyzing and understanding these TTPs, you can dramatically enhance your security program.

 

Author Comment

by:tombombadilll
ID: 9911619
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;
}
0
 
LVL 25

Accepted Solution

by:
James Rodgers earned 300 total points
ID: 9912313
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)">
0
 

Author Comment

by:tombombadilll
ID: 9912387
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?

0
 
LVL 16

Assisted Solution

by:jaysolomon
jaysolomon earned 100 total points
ID: 9912455
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>
0
 
LVL 25

Assisted Solution

by:James Rodgers
James Rodgers earned 300 total points
ID: 9912457
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>
0
 
LVL 25

Expert Comment

by:James Rodgers
ID: 9919812
thanks for the points
0
 

Author Comment

by:tombombadilll
ID: 9919836
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.
0

Featured Post

How to improve team productivity

Quip adds documents, spreadsheets, and tasklists to your Slack experience
- Elevate ideas to Quip docs
- Share Quip docs in Slack
- Get notified of changes to your docs
- Available on iOS/Android/Desktop/Web
- Online/Offline

Join & Write a Comment

Introduction Since I wrote the original article about Handling Date and Time in PHP and MySQL (http://www.experts-exchange.com/articles/201/Handling-Date-and-Time-in-PHP-and-MySQL.html) several years ago, it seemed like now was a good time to updat…
Have you tried to learn about Unicode, UTF-8, and multibyte text encoding and all the articles are just too "academic" or too technical? This article aims to make the whole topic easy for just about anyone to understand.
Viewers will learn about arithmetic and Boolean expressions in Java and the logical operators used to create Boolean expressions. We will cover the symbols used for arithmetic expressions and define each logical operator and how to use them in Boole…
The viewer will learn the benefit of using external CSS files and the relationship between class and ID selectors. Create your external css file by saving it as style.css then set up your style tags: (CODE) Reference the nav tag and set your prop…

708 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

13 Experts available now in Live!

Get 1:1 Help Now