如何使用JavaScript验证此HTML表单?

时间:2022-10-30 14:35:18

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.

我正在使用这个HTML表单,我正在尝试验证字段。我想使用JavaScript检查每个字段是否为空。如果该字段为空,我希望显示隐藏的关联div。

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?

当前问题:如果两个字段都留空,则只显示proName的第一个div,而不显示第二个div。我怎样才能让它们出现?

 <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!

谢谢!

5 个解决方案

#1


3  

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
}

#2


1  

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:

但是,如果您确实要在客户端验证表单,则可以使用HTML5表单验证:

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

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

required属性告诉浏览器该字段是必需的。

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

确保使用HTML5 DOCTYPE( )。

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

示例:http://jsbin.com/ubuqan/1/edit

#3


0  

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

看看validateForm()的作用会很有帮助......我认为它需要成为两种验证方法的包装器,并在一次调用中确定要显示哪个div。目前的情况是,如果validateProName返回false,则不需要执行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...

我会让它做类似下面的事情,它将validateProName和validateCompName的值分配给局部变量,然后如果值为false则显示它们的div。然后,您将简化现有方法......

<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>

#4


0  

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

安德鲁

#5


-1  

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:

然后你只需要一个函数来显示div:

<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.

这假设任何时候你有一个文本字段,它也会有一个带有相同名称的伴随DIV,前面带有“alert”。

#1


3  

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
}

#2


1  

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:

但是,如果您确实要在客户端验证表单,则可以使用HTML5表单验证:

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

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

required属性告诉浏览器该字段是必需的。

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

确保使用HTML5 DOCTYPE( )。

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

示例:http://jsbin.com/ubuqan/1/edit

#3


0  

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

看看validateForm()的作用会很有帮助......我认为它需要成为两种验证方法的包装器,并在一次调用中确定要显示哪个div。目前的情况是,如果validateProName返回false,则不需要执行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...

我会让它做类似下面的事情,它将validateProName和validateCompName的值分配给局部变量,然后如果值为false则显示它们的div。然后,您将简化现有方法......

<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>

#4


0  

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

安德鲁

#5


-1  

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:

然后你只需要一个函数来显示div:

<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.

这假设任何时候你有一个文本字段,它也会有一个带有相同名称的伴随DIV,前面带有“alert”。