JavaScript form validation example

JavaScript form validation example

HTML forms are commonly used to collect user information such as name, email address, location, age, etc.

But it is likely that some users may not enter the data you expect. HTML form validation can be done via JavaScript.

To avoid unnecessary pressure on server resources, you can use JavaScript to validate the form data on the client (user system). Incorrect information will not be submitted to the backend server - this is called client-side validation. This article will introduce this verification

Form validation is generally divided into two methods.

Client-side validation: Execute JS directly on the client to perform validation. There is no interaction with the server during the validation process.

Server-side verification: The page sends the verification information back to the server, which performs verification and sends the verification result back to the client.

Both verifications are necessary because the client-side verification security is not very high, but it can prevent more than 80% of user misoperations, reduce the pressure on the server, and is very fast, providing a high user experience. Don't think that you don't need server-side verification if you have client-side verification. Client-side verification is very easy to bypass. Server-side verification is more secure, so generally both verifications need to be written. 】

Example 1: A simple example

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Simple form validation example</title>
</head>
<head>
<script>
function validateForm(){
var x=document.forms["myForm"]["fname"].value;
if (x==null || x==""){
  //alert("Name must be filled in");
  usernameerror.innerHTML="<font color='red'>Name is required</font>";
  return false;
  }
else{
  usernameerror.innerHTML="correct";
  return true;
  }  
 
}
</script>
</head>
<body>
<!-- 
<form name="myForm" action="demo-form.php" onsubmit="return validateForm()" method="post">
-->
<form name="myForm" onsubmit="return validateForm()" >
Name: <input type="text" name="fname" id="username">
<span id="usernameerror"></span>
<br>
<input type="submit" value="Submit">
<input type="reset" value="Reset">
</form>
 
</body>
</html>

Save the file name: Form verification example 1.html

Run the test with a browser and the results are as follows:

Example 2: A more complex example

<!DOCTYPE html>
<html>
<head>
  <meta charset="UTF-8">
  <title>Form Validation Example Register User</title>
  
  <style type="text/css">
  </style>
 
  <script>
    function checkusername()
    {
      var myform = document.getElementById("form1");
      var username = myform.username.value.length;
      if(username < 1||username>12)
      {
        errusername.innerHTML = "<font color='red'>Username does not meet the requirements</font>";
        return false;
      }else{
        errusername.innerHTML = "<font color='green'>Username meets the requirements</font>";
        return true;
      }
    }
    function checkage()
    {
      var myform = document.getElementById("form1");
      var age = myform.age.value;
      if(age != parseInt(age))
      {
        errage.innerHTML = "<font color='red'>Age does not meet the requirements</font>";
        return false;
      }else{
        errage.innerHTML = "<font color='green'>Age meets the requirements</font>";
        return true;
      }
    }
    function checkemail()
    {
      var myform = document.getElementById("form1");
      var mail=/^[A-Za-z0-9_-]+@[a-zA-Z0-9_-]+(\.[a-zA-Z0-9_-]+)+$/;
      if(!mail.test(myform.email.value))
      {  
        erremail.innerHTML = "<font color='red'>email does not meet the requirements</font>";
        return false;
      }else{
        erremail.innerHTML = "<font color='green'>email meets the requirements</font>";
        return true;
      }
    }
    function checkform()
    {
      checkusername();checkage();checkemail();
      if(checkusername()&&checkage()&&checkemail())
      {
        return true;  
      }else{
        return false;
      }
    }
  </script>
</head>
 
<body>
<!--
 <form id="form1" name="form1" method="post" action="ttt.jsp" onsubmit="return checkform()">
-->
 
 <form id="form1" name="form1" method="post" onsubmit="return checkform()">
<table width="777" border="0" cellpadding="1" cellspacing="1">
 <tr>
  <td colspan="3" ><div align="center">Please enter your registration information</div></td>
 </tr>
 <tr>
  <td width="250" ><div align="right" >Please enter your username: </div></td>
  <td width="250"><div align="center">
     <input type="text" name="username" onblur="checkusername()" />  
   </div></td>
  <td><div id="errusername" align="center"></div></td>
 </tr>
 <tr>
  <td width="250"><div align="right">Please enter your age:</div></td>
  <td width="250"><div align="center" >
   <label>
   <input type="text" name="age" onblur="checkage()"/>
   </label>
  </div></td>
   <td><div align="center" id="errage"></div></td>
 </tr>
 <tr>
  <td width="250"><div align="right" >Please enter your EMAIL:</div></td>
  <td width="250"><div align="center" >
   <label>
   <input type="text" name="email" onblur="checkemail()" />
   </label>
  </div></td>
   <td><div align="center" id="erremail"></div></td>
 </tr>
 <tr>
  <td><div align="right">
   <label>
   <input type="submit" name="Submit" value="Submit" />
   </label>
  </div></td>
   <td><div align="center">
    <label>
    <input type="reset" name="Submit2" value="Reset" />
    </label>
   </div></td>
  <td><div align="center"></div></td>
 </tr>
</table>
 
</form>
 
</body>
</html>

Save the file name: Form verification example 1.html

Run the test with a browser and the results are as follows:

The above is the full content of this article. I hope it will be helpful for everyone’s study. I also hope that everyone will support 123WORDPRESS.COM.

You may also be interested in:
  • Native js implements regular validation of the form (submit only after validation)
  • Native js to implement form validation function
  • Implementing form validation with JavaScript
  • JS simple form validation function complete example
  • Example code for using JavaScript to validate a form using form elements
  • JavaScript implements form registration, form validation, and operator functions
  • A complete example of simple form validation implemented by JS
  • Simple form validation function example implemented by JS
  • JavaScript basic form validation example (pure Js implementation)
  • Implementing form validation with JavaScript

<<:  Detailed explanation of the difference between alt and title

>>:  Tutorial on using the frameset tag in HTML

Recommend

Detailed explanation of ECharts mouse event processing method

An event is an action performed by the user or th...

jQuery achieves large-screen scrolling playback effect

This article shares the specific code of jQuery t...

Setting up a proxy server using nginx

Nginx can use its reverse proxy function to imple...

Vue implements automatic jump to login page when token expires

The project was tested these days, and the tester...

How to install Docker and configure Alibaba Cloud Image Accelerator

Docker Installation There is no need to talk abou...

10 SQL statement optimization techniques to improve MYSQL query efficiency

The execution efficiency of MySQL database has a ...

The most comprehensive collection of front-end interview questions

HTML+CSS 1. Understanding and knowledge of WEB st...

MySQL 4 methods to import data

1. Import mysql command The mysql command import ...

How to change the color of the entire row (tr) when the mouse stops in HTML

Use pure CSS to change the background color of a ...

Markup validation for doctype

But recently I found that using this method will c...

Service management of source package installation under Linux

Table of contents 1. Startup management of source...

Website User Experience Design (UE)

I just saw a post titled "Flow Theory and Des...

How to implement the singleton pattern in Javascript

Table of contents Overview Code Implementation Si...

Detailed explanation of error handling examples in MySQL stored procedures

This article uses an example to describe the erro...