javascript 表单提交和验证的方法

一、使用submit按钮,结合onsubmit事件实现

点击提交表单的时候,触发onsubmit的事件,这个事件会调用checkForm函数,该函数用于判断用户名是否为空

当我们点击提交表单时,将会触发onsubmit事件

onsubmit里是return checkForm,即调用checkForm函数

该函数用于判断用户名是否为空

对于onsubmit,如果return的是false,就会取消提交的操作

如果return的是true,就会执行提交的操作,然后去找action里面的login.php

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">>
    <title>Hello</title>
    <script type="text/javascript">
        function checkForm() {
        // body...
            if( document.form1.username.value == ""){
                window.alert("用户名不能为空");
                return false;
            }else{
                window.alert("用户名不为空,验证通过");
                return true;
            }
        }
    </script>>
</head>
<body>
    <form name="form1" method="post" action="login.php" onsubmit="return checkForm()">
        用户名:<input type="text" name="username">
	密码:<input type="password" name="userpwd">
	<input type="submit" name="提交表单">
    </form>
</body>
</html>

二、submit按钮,结合onclick事件,实现表单的验证和提交

<!DOCTYPE html>
<html>
<head>
	<meta charset="utf-8">>
	<title>Hello</title>
	<script type="text/javascript">
		function checkForm() {
			// body...
			if( document.form1.username.value == ""){
				window.alert("用户名不能为空");
				return false;
			}else{
				window.alert("用户名不为空,验证通过")
				return true;
			}
		}
	</script>>
</head>
<body>
	<form name="form1" method="post" action="login.php" >
	用户名:<input type="text" name="username">
	密码:<input type="password" name="userpwd">
	<input type="submit" name="提交表单" onclick="checkForm()">
	</form>
</body>
</html>

三、button普通按钮,结合submit方法,实现表单验证提交

<!DOCTYPE html>
<html>
<head>
	<meta charset="utf-8">>
	<title>Hello</title>
	<script type="text/javascript">
		function checkForm() {
			// body...
			if( document.form1.username.value.length == 0){
				window.alert("用户名不能为空");
			}else if (document.form1.username.value.length < 5 || document.form1.username.value.length > 20){
				window.alert("用户名只能介于5到20个字符");
			}else if (checkOtherChar(document.form1.username.value)){
				window.alert("用户名中含有特殊符号");
			}else{
				window.alert("验证通过");
				document.form1.submit();
			}
		}
	</script>>
</head>
<body>
	<form name="form1" method="post" action="login.php" >
	用户名:<input type="text" name="username">
	密码:<input type="password" name="userpwd">
	<input type="button" name="提交表单" onclick="checkForm()">
	</form>
</body>
</html>


分类:开发日记 时间:2026年01月22日 浏览:64
发表评论