Simple form validation implemented by javascript

  • 2020-07-21 06:57:47
  • OfStack

Form validation is almost indispensable. Some form validation is done in the background, while others use JavaScript to do basic validation in the front, which can effectively relieve the pressure on the server. The following is the simplest form validation implemented by JS. Code examples are as follows:


<!DOCTYPE html>
<html>
<head>
<meta charset=" utf-8">
<title> The home of the script </title>
<script type="text/javascript"> 
function chkform(){ 
 if(document.getElementById("username").value==""){ 
  alert(" User name cannot be empty! "); 
  return false; 
 } 
 if(document.getElementById("pw").value=="") { 
  alert(" Password cannot be empty! "); 
  return false; 
 } 
} 
</script> 
</head> 
<body> 
<form action="" name="myform"> 
 <table> 
  <tr> 
   <td> The user name :</td> 
   <td><input type="text" name="username" id="username" /></td> 
  </tr> 
  <tr> 
   <td> password :</td> 
   <td><input type="password" name="pw" id="pw" /></td> 
  </tr> 
  <tr> 
   <td colspan="2"><input type="submit" value=" submit "></td> 
  </tr> 
 </table> 
</form> 
</body> 
</html>

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

1. In the JavaScript code, create the chkform() function to verify the form.


document.getElementById("username").value

The above code can get id username for the value of the object, and then by if statement whether this value is empty, if the null return false, this statement is very important, even if the form content is empty, the form will be submitted, also will not verify the result, the role of second if judgment statements, too, will not covered here.

2.onclick="return chkform()", which validates the form by executing the chkform() function when the submit button is clicked.

This is the end of this article, I hope you enjoy it.


Related articles: