JavaScript form validation



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

Form data often requires the use of JavaScript to verify its correctness:


  • Verify whether the form data is empty?


  • Verify whether the input is a correct email address?


  • Verify that the date is entered correctly?


  • #Verify whether the form input content is numeric?



Required (or required) items

The following function is used to check whether the user has filled in the required (or required) fields in the form. Select) project. If it is required or the required field is empty, then the warning box will pop 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("姓必须填写");
		return false;
	}
}

The above function is in the form Called when the form is submitted:

Instance

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>php中文网(php.cn)</title>
</head>
<head>
<script>
function validateForm(){
var x=document.forms["myForm"]["fname"].value;
if (x==null || x==""){
  alert("姓必须填写");
  return false;
  }
}
</script>
</head>
<body>
	
<form name="myForm" action="demo-form.php" onsubmit="return validateForm()" method="post">
姓: <input type="text" name="fname">
<input type="submit" value="提交">
</form>
	
</body>
</html>

Run Instance»

Click the "Run Instance" button to view the online instance


E-mail Validation

The following function checks whether the entered data conforms to the basic syntax of an email address.

This means that the input data must contain the @ symbol and the period (.). At the same time, @ cannot be the first character of the email address, and there must be at least one period after @:

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("不是一个有效的 e-mail 地址");
		return false;
	}
}

The following is the complete code together with the HTML form:

Example

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>php中文网(php.cn)</title>
</head>
<head>
<script>
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("不是一个有效的 e-mail 地址");
  		return false;
	}
}
</script>
</head>
<body>
	
<form name="myForm" action="demo-form.php" onsubmit="return validateForm();" method="post">
Email: <input type="text" name="email">
<input type="submit" value="提交">
</form>
	
</body>
</html>

Run Instance»

Click the "Run Instance" button to view the online instance