简体   繁体   English

如何验证简单的Web表单

[英]How to validate a simple web form

Im working on a small form and using js to validate if the fields are empty or not. 我正在以小形式工作,并使用js来验证字段是否为空。 I have a span class next to the name field "name" "email ". 我在名称字段“ name” “ email ”旁边有一个span类。

For the "name" field, i have a span class called "error" . 对于“名称”字段,我有一个名为“错误”的跨度类。

For the "email" field, i have another span class called "error2". 对于“电子邮件”字段,我还有另一个跨度类称为“ error2”。

what can i do to only use one class to display the "error message" , because of course i will have more field and I don't want to keep adding more classes. 我该怎么做才能只使用一个类来显示“错误消息” ,因为我当然会有更多的字段,而且我不想继续添加更多的类。 error3, error4 错误3,错误4

HTML: HTML:

 <form action="#i" name="myForm" onsubmit="return(validate());">
  Name: <span id="error"></span><br>
  <input type="text" name="Name" /><br><br> 

  EMail: <span id="error2"></span><br>
  <input type="text" name="EMail" /><br> <br> 

  <input type="submit" value="Submit" /> <br>
  </form>

JS: JS:

  function validate()
  {
     var t = 0;      
     if( document.myForm.Name.value == "" )
     {
        document.getElementById('error').innerHTML = "<br>Empty";  
        t = 1;
     }

     if( document.myForm.EMail.value == "" )
     { 
        document.getElementById('error2').innerHTML = "<br>Empty";  
        t = 1;
     }

     if(t == 1)
     {
        return false;
     }
     else
        return true;
  } 

Instead of giving the spans the attribute of Id, use classes instead. 不要给spans赋予Id属性,而要使用类。 So for example, you can define ALL your spans as follows: 因此,例如,您可以定义所有跨度,如下所示:

 <span class="error"> ... </span>

Then, in your validate function, you can obtain these spans through: 然后,在您的validate函数中,您可以通过以下方式获得这些范围:

document.getElementsByClassName('error');

Keep in mind though, this returns an array, which would actually be perfect for your function. 但是请记住,这将返回一个数组,该数组实际上对于您的函数而言是完美的。 This way, you can write a basic for-loop to go through each span and make sure each field is filled in correctly. 这样,您可以编写一个基本的for循环来遍历每个范围,并确保正确填写每个字段。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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