Javascript validation form help.

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • Jacob Clements
    New Member
    • Nov 2011
    • 5

    Javascript validation form help.

    Hello,
    I am very new to Javascript and I've only understanding for simple Javascript.

    I had to develop a Javascript validation form for a project. I have done so, using the most simple methods. After submitting the form, the appropriate errors show, but, when resubmitted, the errors are not updated (they are still present). I've had a few ideas about fixing this, but I'm so new to Javascript that my knowledge of commands are restricted heavily. I have seen other functioning forms but most are a lot more complex than mine. Is there a simple rule I can incorporate to fix my Javascript form? I'm guessing I'll need another function.


    Now, the web page (and even the form) is quite large, so I'll just show the script:
    Code:
    <script type="text/javascript" language="javascript">
    // This form is only a 'template'. The server has not been manipulated to process the results yet.
    
    function Validateform(f1)
    {
    if (document.f1.firstname.value=="")
    {
    document.getElementById("e1").innerHTML="* Error: Please Enter your first name ";
    }
    
    if (document.f1.lastname.value=="")
    {
    document.getElementById("e2").innerHTML="* Error: Please Enter your last name ";
    }
    
    if (document.f1.a1.value.length<4)
    {
    document.getElementById("e3").innerHTML="* Error: Please Enter your address (it must be longer than 4 characters) ";
    }
    
    if (document.f1.city.value=="")
    {
    document.getElementById("e4").innerHTML="* Error: Please Enter your City ";
    }
    
    if (document.f1.postcode.value.length!=4)
    {
    document.getElementById("e5").innerHTML="* Error: Please Enter your postcode (4 digits) ";
    }
    
    if (document.f1.phone.value=="")
    {
    document.getElementById("e6").innerHTML="* Error: Please Enter your phone number ";
    }
    
    if ((document.f1.d1[0].checked==false) && (document.f1.d1[1].checked==false) && (document.f1.d1[2].checked==false))
    {document.getElementById("e7").innerHTML="* Error: Please Enter your chosen payment cost ";}
    
    if ((document.f1.p1[0].checked==false) && (document.f1.p1[1].checked==false) && (document.f1.p1[2].checked==false) && (document.f1.p1[3].checked==false))
    {document.getElementById("e8").innerHTML="* Error: Please Enter your chosen payment method ";}
    if ((document.f1.lastname.value=="") || (document.f1.firstname.value=="") || (document.f1.a1.value.length<4) || (document.f1.city.value=="") || (document.f1.postcode.value.length!=4) || ((document.f1.d1[0].checked==false) && (document.f1.d1[1].checked==false) && (document.f1.d1[2].checked==false)) || ((document.f1.p1[0].checked==false) && (document.f1.p1[1].checked==false) && (document.f1.p1[2].checked==false) && (document.f1.p1[3].checked==false)))
    {
    return false;
    }
    
    return true;
    // This is a very simple validation function and it does have an annoying fault. The Errors do not update once solved.
    }
    </script>
  • Jacob Clements
    New Member
    • Nov 2011
    • 5

    #2
    Oh and I know that I should have made variables for the directories..

    Comment

    • acoder
      Recognized Expert MVP
      • Nov 2006
      • 16032

      #3
      There are better ways to do this, but let's just work with your code first.

      You need to add else to set the error message to "" when there's no error, e.g.
      Code:
      if (f1.firstname.value=="")
      {
      document.getElementById("e1").innerHTML="* Error: Please Enter your first name ";
      } else {
      document.getElementById("e1").innerHTML="";
      }
      Notice I replaced document.f1 with f1. If you're passing 'f1' as a parameter to the validation function, you can use it to access the form elements.

      Comment

      • Jacob Clements
        New Member
        • Nov 2011
        • 5

        #4
        Originally posted by acoder
        There are better ways to do this, but let's just work with your code first.

        You need to add else to set the error message to "" when there's no error, e.g.
        Code:
        if (f1.firstname.value=="")
        {
        document.getElementById("e1").innerHTML="* Error: Please Enter your first name ";
        } else {
        document.getElementById("e1").innerHTML="";
        }
        Notice I replaced document.f1 with f1. If you're passing 'f1' as a parameter to the validation function, you can use it to access the form elements.
        Thankyou, that was much easier than expected. I'll just re-write the code and then chose your answer as best.
        Thanks again.

        Comment

        • omerbutt
          Contributor
          • Nov 2006
          • 638

          #5
          Hi Jacob ,
          you might look this function to make the validation code more optimised
          Code:
          function getForms(){
          
          	var fobj=document.forms["form_name"];
          
          	var str="";
          
          	for(var i=0; i<=fobj.elements.length-1;i++){
          
          		switch(fobj.elements[i].type){
          
          			case "text":
          
          				if(fobj.elements[i].value==""){
          				str += "Please Enter "+ fobj.elements[i].name + "&";
          }
          			break;
          
          			case "textarea":
          
          if(fobj.elements[i].value==""){
          				str += "Please Enter "+  fobj.elements[i].name + "&";
          }
          			break;
          
          			case "hidden":
          
          if(fobj.elements[i].value==""){
          				str += "Please Enter "+  fobj.elements[i].name + "\n";
          }
          			break;
          
          			case "checkbox":
          
          if(!fobj.elements[i].checked){
          
          				str +="Please Enter "+fobj.elements[i].checked + "\n";
          
          			break;
          
          			case "select-one":
          if(fobj.elements[i].options[fobj.elements[i].selectedIndex].value=="none"){
          				str += "Please Enter "+ fobj.elements[i].id+"\n";
          }
          
          			break;
          
          		}
          
          	}
          
          	if(str!=""){
          alert(str);
          return false;
          }else{
          fobj.submit();
          }
          
          }
          Last edited by omerbutt; Nov 28 '11, 10:23 PM. Reason: changed code for the

          Comment

          • Jacob Clements
            New Member
            • Nov 2011
            • 5

            #6
            Thankyou for this code, I will try to use it, however there are heaps of functions I don't understand.

            Will the following code return 'false' for an action in the form itself?
            Code:
            else{ 
            fobj.submit;
            To be honest, I do not even understand the case and break command.

            Comment

            • omerbutt
              Contributor
              • Nov 2006
              • 638

              #7
              try replacing the else part with this code
              Code:
              fobj.action="save-data.php";
              fobj.method="post";
              fobj.submit();
              and what do you mean by saying that will it return false for an action , do you mean that the form submits when returned false or true then i will say yes but it needs that the javascript function should be called in the onsubmit attribute of the form like this
              Code:
              <form name='form_name' action='file.php' onsubmit='return function validation();'>
              and we need to have a input type submit inside that for note this that the input type should not be button but submit
              regards,
              Omer Aslam

              Comment

              • Jacob Clements
                New Member
                • Nov 2011
                • 5

                #8
                Now, I see you have edited the code to add the return false statement, but I do not know why I would need this:
                Code:
                fobj.action="save-data.php"; 
                fobj.method="post"; 
                fobj.submit();
                Also, acoder's method works fine, I just have no clue how your code works and I was curious. Sorry if I'm a bit foolish, but it's just that you introduced a whole new range of functions and statements that I have no clue about.

                Comment

                • omerbutt
                  Contributor
                  • Nov 2006
                  • 638

                  #9
                  hi Jacob,
                  no worries , let me explain , first of all forms can be submitted into, i would say 4 different ways,
                  1. Normal for submission with a input type submit with a page reload.
                  2. Submit a form via javascript with a input type button using onclick event with a page reload.
                  3. Submit a form via Ajax/javascript with a input type button using onclick event without page reload.
                  4. Submit a form via Ajax/javascript with a submit type button using onsubmit event without page reload.

                  1.Normal for submission with a page reload.

                  Code:
                  <form name='myForm' id='myForm' action='saveData.php'>
                      <input type='text' value='' name='name' id='name' />
                      <input type='text' value='' name='age' id='age' />
                      <input type='submit' value='Submit' name='submit' id='submit' />
                  </form>
                  In this we have a form with some inputs and a submit type button to submit the form, when the submit button is clicked the form is submitted to the page saveData.php that is specified in the action attribute to save the form data, all of them inside the form tag after the word form are called attributes,
                  ie.
                  <form name='myForm' id='myForm' action='saveDat a.php'>

                  now you donot need any javascript to submit the form but if you need to validate the form with this method you need to use the onsubmit attribute that you can add in the form tag like this
                  Code:
                  <form name='myForm' id='myForm' action='saveData.php' onsubmit='validateInput()'>
                  now if the validation fails then you need to return false to the form so that the form is not submitted and the user should provide the appropriate inputs where required, and to do that you will do all the necessary validation inside your validateInput() function and then in the end return true or false depending on the validation success or failure.

                  2. Submit a form via javascript with a input type button using onclick event with a page reload.


                  Code:
                  <form name='myForm' id='myForm' action='saveData.php'>
                      <input type='text' value='' name='name' id='name' />
                      <input type='text' value='' name='age' id='age' />
                      <input type='button' value='Submit' name='submit' id='submit' onclick='submitForm();' />
                  </form>
                  In this we have a form with some inputs and a input with type button to submit the form, when the button is clicked the onclick event of the button calls the submitForm() function where i would like to refer my own function that i posted before
                  [code=javascript]
                  function submitForm(){
                  // do your regular validation and save the result(true or false)
                  var a=validateInput ();

                  if(a){
                  fobj.action="sa ve-data.php";
                  fobj.method="po st";
                  fobj.submit();
                  }

                  }

                  function validateInput() {
                  var fobj=document.f orms["form_name"];
                  var str="";
                  for(var i=0; i<=fobj.element s.length-1;i++){
                  switch(fobj.ele ments[i].type){
                  case "text":
                  if(fobj.element s[i].value==""){
                  str += "Please Enter "+ fobj.elements[i].name + "&";
                  }
                  break;

                  case "textarea":
                  if(fobj.element s[i].value==""){
                  str += "Please Enter "+ fobj.elements[i].name + "&";
                  }
                  break;
                  case "hidden":
                  if(fobj.element s[i].value==""){
                  str += "Please Enter "+ fobj.elements[i].name + "\n"; }
                  break;
                  case "checkbox":
                  if(!fobj.elemen ts[i].checked){
                  str +="Please Enter "+fobj.elem ents[i].checked + "\n";
                  break;
                  case "select-one": if(fobj.element s[i].options[fobj.elements[i].selectedIndex].value=="none") {
                  str += "Please Enter "+ fobj.elements[i].id+"\n";
                  }
                  break;
                  }
                  }
                  if(str!=""){
                  alert(str);
                  return false;
                  }else{
                  return true;
                  }
                  }
                  [/code]


                  now when you see the inputValidate() function the first line
                  Code:
                   var fobj=document.forms["form_name"];
                  what it dies that it makes the object of the form that includes the collection of the form elements , all those input,textarea, select and all other valid form elements that are written inside the form are the form elements now the form object that is created and stored inside the fobj variable is used to access all the form elements and attributes also ,all those things related to the form , now the next insight statement that would confuse you is the
                  Code:
                  for(var i=0; i<=fobj.elements.length-1;i++)
                  the thing that bugged you is
                  Code:
                  fobj.elements.length
                  i hope not the for loop (:D),
                  now let us explain in two steps first what this statement does, it calculates the length of the form, length of the form is the number of elements present in the form, so as we know that fobj has the form elements
                  collection we will access the elements via elements array inside the fobj, which is done like
                  Code:
                  fobj.elements
                  and length is the key word which returns the length of any array, so to get to know that how many elements are there in the form we created the fobj (form object) and then accessed the elements array's length elements.length . Now what so far is done is we created the fobj and made a for loop to iterate till the size of the form elements , inside the for loop we have a switch statement
                  Code:
                  switch(fobj.elements[i].type)
                  what is a switch statement?,

                  In computer programming, a switch, case, select or inspect statement is a type of selection control mechanism that exists in most imperative programming languages such as Pascal, Ada, C/C++, C#, Java, and so on. It is also included in several other types of languages. Its purpose is to allow the value of a variable or expression to control the flow of program execution via a multiway branch (or "goto", one of several labels). The main reasons for using a switch include improving clarity, by reducing otherwise repetitive coding, and (if the heuristics permit) also offering the potential for faster execution through easier compiler optimization in many cases.

                  I would recommend you to go and watch some examples for a switch statement before proceeding any further .......till this point any questions in your mind , if not i will proceed with the explanation in the next post ,

                  regards,
                  Omer Aslam

                  Comment

                  • acoder
                    Recognized Expert MVP
                    • Nov 2006
                    • 16032

                    #10
                    I think a simple return true; should suffice. There's no need to use the submit() method because you have return in onsubmit.

                    Comment

                    • omerbutt
                      Contributor
                      • Nov 2006
                      • 638

                      #11
                      yes acoder you are right, but at that time i was referring to submit with onclick as i have been explaining in the last post
                      regards,
                      Omer Aslam

                      Comment

                      Working...