Home >Web Front-end >JS Tutorial >How to implement form validation in JavaScript
This article will share about the application of form validation in JavaScript. It has a certain reference function and I hope it will be helpful to everyone.
In JavaScript, we can send the data to the server Validate these input data in the HTML form before. Client-side form validation is usually done using JavaScript. For most users, JavaScript form validation will save a lot of time, but if the user has JavaScript turned off, they still need to double-check the data on the server. The form data usually checked by JavaScript are:
(1) Whether the user has filled in the required items in the form
(2) Whether the email address entered by the user is legal
(3) Whether the user has entered the password in the correct format
(4) Whether the user has entered text in the data field
Next, I will tell you how to use form validation in JavaScript through actual cases
htmlcode
<table style="width:350px;height:200px;margin: 100px auto;border:1px solid #ccc;"> <tr> <td> 用户名:<input type="text" name="username" id="txt"> </td> <td id="sure"></td> </tr> <tr> <td> 密码 :<input type="password" name="password" id="mima"> </td> <td id="sure1"></td> </tr> </table>
Verify whether the user name and password are entered correctly
<script type="text/javascript"> var txt=document.getElementById("txt"); var sure=document.getElementById("sure"); var mima=document.getElementById("mima"); var sure1=document.getElementById("sure1"); txt.onblur=function(){ if(this.value=="") { sure.style.display="block"; sure.style.color="red"; sure.innerHTML="输入内容不能为空"; } else if((txt.value.length<3)||(txt.value.length>8)){ sure.style.display="block"; sure.style.color="red"; sure.innerHTML="您输入的用户名是错误的长度"; } else{ sure.style.display="block"; sure.style.color="#444" sure.innerHTML="输入正确"; } } mima.onblur=function(){ if(this.value=="") { sure1.style.display="block"; sure1.style.color="red"; sure1.innerHTML="输入内容不能为空"; } else if((txt.value.length<3)||(txt.value.length>8)){ sure1.style.display="block"; sure1.style.color="red"; sure1.innerHTML="您输入的密码是错误的长度"; } else if(isNaN(this.value)){ sure1.style.display="block"; sure1.style.color="red"; sure1.innerHTML="请输入数字"; } else{ sure1.style.display="block"; sure1.style.color="#444" sure1.innerHTML="输入正确"; } }
When the input content is incorrect
Summary: The above is the entire content of this article, I hope it will help everyone learn form verification Helps.
The above is the detailed content of How to implement form validation in JavaScript. For more information, please follow other related articles on the PHP Chinese website!