Home  >  Article  >  Web Front-end  >  Simple form validation implemented in javascript_javascript skills

Simple form validation implemented in javascript_javascript skills

WBOY
WBOYOriginal
2016-05-16 15:50:47967browse

Form verification is almost indispensable. Some form verification is completed in the background, and some use JavaScript to complete basic verification on the front end. This can effectively reduce the pressure on the server. Here is an introduction to the JS implementation The simplest form validation. The code example is as follows:

<!DOCTYPE html>
<html>
<head>
<meta charset=" utf-8">
<title>脚本之家</title>
<script type="text/javascript"> 
function chkform(){ 
 if(document.getElementById("username").value==""){ 
  alert("用户名不能为空!"); 
  return false; 
 } 
 if(document.getElementById("pw").value=="") { 
  alert("密码不能为空!"); 
  return false; 
 } 
} 
</script> 
</head> 
<body> 
<form action="" name="myform"> 
 <table> 
  <tr> 
   <td>用户名:</td> 
   <td><input type="text" name="username" id="username" /></td> 
  </tr> 
  <tr> 
   <td>密码:</td> 
   <td><input type="password" name="pw" id="pw" /></td> 
  </tr> 
  <tr> 
   <td colspan="2"><input type="submit" value="提交"></td> 
  </tr> 
 </table> 
</form> 
</body> 
</html>

The above code implements the most basic form verification, that is, the form content is not allowed to be empty. Here is a brief introduction to its implementation process:

1. In JavaScript code, create the chkform() function to verify the form. Here is a brief introduction to the function:

document.getElementById("username").value

The above code can get the value of the object with id username, and then use the if statement to determine whether the value is empty. If it is empty, return false. This statement is very important, otherwise the form will be submitted even if the form content is empty. , the verification effect will not be achieved. The same is true for the second if judgment statement, which will not be introduced here.

2.onclick="return chkform()", the function of this statement is that when the submit button is clicked, the chkform() function will be executed to verify the form. It is particularly emphasized here that don't forget to add return.

The above is the entire content of this article, I hope you all like it.

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn