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>

  • 5
    点赞
  • 42
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值