Javascript实现简单的表单验证

 

<!DOCTYPE html>
<html>

	<head>
		<meta charset="UTF-8">
		<title>表单验证</title>
		<script>
			function validateName() {
				//所有的表单项元素都value属性
				var name = document.getElementById("userName").value;
				var msg = document.getElementById("nameMsg");
				if(name == null || name == "") {
					msg.innerHTML = "用户名不能为空!";
					msg.style.color = "red";
					return false;
				} else if(name.length < 6) {
					msg.innerHTML = "用户名长度必须为大于6的!";
					msg.style.color = "red";
					return false;
				}
				msg.innerHTML = "用户名可用";
				msg.style.color = "green";
				return true;
			}

			function validatePwd() {
				var password1 = document.getElementById("password1").value;
				var msg = document.getElementById("pwdMsg1");
				if(password1 == null || password1 == "") {
					msg.innerHTML = "密码不能为空!";
					msg.style.color = "red";
					return false;
				} else if(password1.length < 8) {
					msg.innerHTML = "密码的长度必须为大于8的!";
					msg.style.color = "red";
					return false;
				}
				msg.innerHTML = "密码合法";
				msg.style.color = "green";
				return true;
			}

  			function confirmPwd() {
				var pwd1 = document.getElementById("password1").value;
				var pwd2 = document.getElementById("password2").value;
				var msg = document.getElementById("pwdMsg2");
				if(pwd1 != pwd2) {
					msg.innerHTML = "两次输入的密码不一致!";
					msg.style.color = "red";
					return false;
				}
				msg.innerHTML = "两次输入的密码一致";
				msg.style.color = "green";
				return true;
			}

			function validateGender() {
				var gender = document.getElementById("gender").value;
				if(gender == -1) {
					alert("性别为必选项!");
					return false;
				}
				return true;
			}

			function register() {
				return
				validateName() && validatePwd() && confirmPwd() && validateGender();
			}
		</script>
	</head>

	<body>
		<h1>注册</h1>
		<form action="提交.html" method="get" onsubmit="return register()">
			用户名:<input type="text" id="userName" placeholder="请输入用户名" onblur="validateName()" />
			<span id="nameMsg">用户名长度至少6位</span><br /> 
			密码:<input type="password" id="password1" placeholder="请输入密码" onblur="validatePwd()" />
			<span id="pwdMsg1">密码长度至少8位</span><br /> 
			确认密码:<input type="password" id="password2" placeholder="请确认密码" onblur="confirmPwd()" />
			<span id="pwdMsg2">确认密码与密码一致</span><br /> 
			性别:<select id="gender">
					<option value="-1">请选择性别</option>
					<option value="0">女</option>
					<option value="1">男</option>
				</select><br /><br />
			<button type="submit">注册</button>
			<button type="reset">重置</button>
		</form>
	</body>
</html>

 

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值