Coding With Fun
Home Docker Django Node.js Articles Python pip guide FAQ Policy

JavaScript form validation


May 06, 2021 JavaScript


Table of contents


JavaScript form validation


JavaScript form validation

JavaScript can be used to validate the input data in HTML forms before it is sent to the server.

Form data often needs javaScript to verify its correctness:


  • Verify that the form data is empty?

  • Verify that the input is a correct email address?

  • Is the verification date entered correctly?

  • Verify that the form input is digital?


Required (or required) items

The following function checks whether the user has filled out the required (or required) items in the form. If the required or required option is empty, the warning box pops up and the return value of the function is false, otherwise the return value of the function is true (meaning there is no problem with the data):

function validateForm()        
{        
var x=document.forms["myForm"]["fname"].value;        
if (x==null || x=="")        
  {        
  alert("First name must be filled out");        
  return false;        
  }        
}

The above function is called when the form form is submitted:

<form name="myForm" action="demo_form.asp" onsubmit="return validateForm()" method="post">
First name: <input type="text" name="fname">
<input type="submit" value="Submit">
</form>

Try it out . . .


E-mail verification

The following function checks whether the data entered conforms to the basic syntax of the e-mail address.

This means that the data entered must contain the sign and dot (.). At the same time, the first character of the e-mail address must not be the first character, and the s must be followed by at least one dot:

function validateForm()        
{        
var x=document.forms["myForm"]["email"].value;        
var atpos=x.indexOf("@");        
var dotpos=x.lastIndexOf(".");        
if (atpos<1 || dotpos<atpos+2 || dotpos+2>=x.length)        
  {        
  alert("Not a valid e-mail address");        
  return false;        
  }       
}

Here's the full code along with the HTML form:

<form name="myForm" action="demo_form.asp" onsubmit="return validateForm();" method="post">
Email: <input type="text" name="email">
<input type="submit" value="Submit">
</form>

Try it out . . .

Digital verification

The following function checks whether the input data is a number between 1 and 10. If you do not enter a number or not, the warning box pops up and the return value of the function is false, otherwise the return value of the function is true (meaning there is no problem with the data):

<form name="myForm" action="demo_form.asp" onsubmit="return validateForm();" method="post">

<strong>请输入1到10之间的数字:</strong>

<input id="number">

<button type="button" onclick="myFunction()">提交</button>

</form>


Try it out . . .

Related articles

JavaScript Standard Reference Tutorial: JavaScript Form