简体   繁体   中英

How do I make this HTML form validate using JavaScript?

I'm working with this HTML form, and I am attempting to validate the fields. I would like to check that each field is not empty using JavaScript. If the field is empty, I want the hidden associated div to be displayed.

CURRENT PROBLEM: If both fields are left empty, only the first div is shown for proName and the second is not revealed. How can I make them both appear?

 <html>
 <body>
 <form action="" method="post" class="form" name="form" onsubmit="return validateForm();">
      <p><label for="proName">Processors Name: </label>
           <input type="text" name="proName" id="proName"></p>
                <div id="alertProName" style="display:none;">
                     <p>Please fill in this field</p>
                </div>

      <p><label for="compName">Company Ordered Through: </label>
           <input type="text" name="compName" id="compName"></p>
                <div id="alertCompName" style="display:none;">
                     <p>Please fill in this field</p>
                </div>
 </form>

 <script type="text/javascript">
 function validateForm() {
      var x=document.forms["form"]["proName"].value;                    

      if (x==null || x=="") {
      var s = document.getElementById("alertProName").style.display="block";
      return false;
      }
 };

 function validateForm() {
      var z=document.forms["form"]["compName"].value;                   

      if (z==null || z=="") {
      var a = document.getElementById("alertCompName").style.display="block";
      return false;
      }
 };
 </script>
 </body>
 </html>

Thank you!

function validateForm(){
  var valid = true;
  var x=document.forms["form"]["proName"].value;                    
  if (x==null || x=="") {
    document.getElementById("alertProName").style.display="block"; //show the error message
    valid = false;
  }else{
    document.getElementById("alertProName").style.display="none"; // hide the error message
  }
  var z=document.forms["form"]["compName"].value;                   

  if (z==null || z=="") {
    document.getElementById("alertCompName").style.display="block";//show the error message
    valid = false;
  }else{
    document.getElementById("alertCompName").style.display="none"// hide the error message
  }
  return valid; // only if both are valid will we submit
}

Validating a form client side is not a good idea because the client can always bypass it.

However, if you really want to validate a form on the client side, you can use HTML5 form validation:

<input type="text" name="somefield" required />

The required attribute tells the browser the the field is required.

Make sure that you use the HTML5 DOCTYPE ( <DOCTYPE HTML> ).

Example: http://jsbin.com/ubuqan/1/edit

It would be helpful to see what validateForm() does...
I think it would need to be a wrapper for both validation methods and determine in one call which div's to show. As things stand at the moment if validateProName returns false it won't need to execute validateCompName

I would have it do something like the following, which assigns the values of both validateProName and validateCompName to local variables and then shows their divs if the value is false. You would then simplify your existing methods...

<script type="text/javascript">
function validateForm() {
  var pro= validateProName();
  var comp = validateCompName();
  if (!pro) {
      var s = document.getElementById("alertProName").style.display="block";
  }
  if (!comp) {
      var a = document.getElementById("alertCompName").style.display="block";
  }
}
</script>

Why not just combine them into one function.

 <script type="text/javascript">
 function validateForm() {
      var x=document.forms["form"]["proName"].value;                    

      if (x==null || x=="") {
      var s = document.getElementById("alertProName").style.display="block";
      return false;

      var z=document.forms["form"]["compName"].value;                   

      if (z==null || z=="") {
      var a = document.getElementById("alertCompName").style.display="block";
      return false;
      }
 };    

Does this achieve what you want?

Andrew

Change your form to this:

<form action="" method="post" class="form" name="form" onsubmit="return validateForm(this);">

Then you just need the one function to display the divs:

<script type="text/javascript">
function validateForm(form) {
    for (e in form.elements) {
        var element = form.elements[e];

        if (element.type == "text") {
            console.log(element.name);
            var elementName = element.name;
            elementName = "alert" + elementName.charAt(0).toUpperCase() + elementName.slice(1);
            var alertElement = document.getElementById(elementName);
            if (alertElement)
                alertElement.style.display = "block";
        }
    }

    return false;
}
</script>

This assumes that anytime you have a text field, it will also have an accompanied DIV with the same name with "alert" prepended.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM