<!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>