Web Analytics Made Easy -
StatCounter Trouble with multiple validation forms - CodingForum

Announcement

Collapse
No announcement yet.

Trouble with multiple validation forms

Collapse
X
 
  • Filter
  • Time
  • Show
Clear All
new posts

  • Trouble with multiple validation forms

    Hello, I'm trying to make a simple webpage with two input text boxes that when submitted when empty, I'll get an error pop-up telling me which ones are empty, both, first name, or last name. When there's only one if, the script works. But when there's multiple else ifs, nothing happens if I press submit. Can someone help me?

    Code:
    <html>
    <head>
    <script type="text/javascript">
    function validateForm()
    {
    var x=document.forms["myForm"]["firstname"].value;
    var y=document.forms["myForm"]["lastname"].value;
    if (x==null || x=="" && y==null || y=="")
      {
      alert("Please put in your first and last name.");
      return false;
      }
    else if (x==null || x=="")
      {
      alert("Please put in your first name.");
      return false;
      }
    else if (y==null || y=="")
      {
      alert("Please put in your last name.");
      return false:
      }
    }
    </script>
    </head>
    
    <body>
    <form name="myForm">
    First name: <input type="text" name="firstname"><br>
    Last name: <input type="text" name="lastname">
    <input type="submit" value="Submit" onclick="validateForm()">
    </form>
    </body>
    
    </html>

  • #2
    Several errors, now corrected:-

    Code:
    <html>
    <head>
    <script type="text/javascript">
    function validateForm() {
    var x=document.forms["myForm"]["firstname"].value;
    var y=document.forms["myForm"]["lastname"].value;
    if ((x==null || x=="") && (y==null || y==""))  {
      alert("Please put in your first and last name.");
      return false;
      }
    else if (x==null || x=="")  {
      alert("Please put in your first name.");
      return false;
      }
    else if (y==null || y=="")  {
      alert("Please put in your last name.");
      return false;
      }
    }
    </script>
    </head>
    
    <body>
    <form name="myForm">
    First name: <input type="text" name="firstname"><br>
    Last name: <input type="text" name="lastname">
    <input type="submit" value="Submit" onclick="return validateForm()">
    </form>
    </body>
    
    </html>

    You should note that form validation of the pattern if (document.forms[0].elements[1].value == "") is barely worthy of the name, and virtually useless, as even a single space, an X or a ? will return false, that is pass the validation. This topic has been covered many times before in this forum.


    Remove cap and push up bottom - Instructions on shaving stick

    All the code given in this post has been tested and is intended to address the question asked.
    Unless stated otherwise it is not just a demonstration.

    Comment

    Working...
    X
    😀
    🥰
    🤢
    😎
    😡
    👍
    👎