SoFunction
Updated on 2025-02-28

Example of simple form validation function implemented by JS

This article describes the simple form verification function implemented by JS. Share it for your reference, as follows:

source code:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http:///TR/xhtml1/DTD/">
<html xmlns="http:///1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Untitled document</title>
<script type="text/javascript" src=""></script>
<link rel="stylesheet" type="text/css" href="" rel="external nofollow" />
</head>
<body>
<form name="f1">
Name:<input type="text" name="xm" />
<br/>
age:<input type="text" name="nl" />
Hobby:<input type= "checkbox" name="ah" />climb mountains
<input type= "checkbox" name="ah" />swim
<input type= "checkbox" name="ah" />tennis
<input type= "checkbox" name="ah" />table tennis
<br/>
password:<input type="password" name="mm"/>
<br/>
重复password:<input type="password" name="cfmm"/>
<br/>
Remark:<textarea name="bz" rows="10" cols="20"></textarea>
<br/>
<input type="button" value="submit" onclick="checkit();"/>
</form>
</body>
</html>

File code:

// JavaScript Document
function checkit()
{ var flag = false;
 for(var i=0;i<[0].;i++)
{
if([0].ah[i].checked)//checked means selected{
flag = true;
break;
}
}
if(!flag)//No hobby was selected{
alert("Please choose at least one hobby!");
return;//If it is not found, go back until it is found!}
if([0].<9)
{
alert("The password must be above 8 digits!");
[0].();//Let the password box get the focus. The focus is that some automated operations can be completed according to the application cooperation, such as entering the wrong username and password when logging in. After turning the login page, the username input box can automatically get the focus to avoid user repositioning.return;
}
if([0].!=[0].)
{
alert("The password inputs are inconsistent when the two times, please re-enter the password!");
return;
}
if([0].=="")
{
alert("Please enter a note!");
}
}

Notice:Use var to declare variables in js, use function to define functions,

This example can achieve Hobby verification (can't be empty), whether the password is consistent, and the length of the password must be greater than 8, and whether the note is empty!

In addition, the css file is handed over to the readers to beautify it themselves~

For more information about JavaScript, readers who are interested in reading this site's special topic:JavaScript form (form) operation skills》、《Summary of JavaScript DOM skills》、《Summary of JavaScript array operation skills》、《Summary of JavaScript mathematical operations usage》、《Summary of JavaScript data structure and algorithm techniques"and"Summary of JavaScript Errors and Debugging Skills

I hope this article will be helpful to everyone's JavaScript programming.