<script>
//定义方法分别校验个个表单项
window.onload = function(){
//给表单绑定unssubmit事件,监听器校验每一个结果
document.getElementById("form").onsubmit = function(){
//调用用户名校验方法checkUsername
//调用密码校验方法checkPassword
return checkUsername()&& checkPassword();
}
//给用户名和密码框分别绑定离焦事件
document.getElementById("username").onblur = checkUsername;
document.getElementById("password").onblur = checkPassword;
}
//用户名校验方法checkUsername
function checkUsername(){
//获取用户名的值
var username = document.getElementById("username").value;
//用正则表达式
var reg = /^\w{6,12}$/;
//判断值是否符合正则的规则
var flag = reg.test(username);
//提示信息
//获取span
var s_username = document.getElementById("s_username");
if(flag){
//提示正确后面绿色
s_username.innerText="y";
s_username.className="dui"
}else{
//提示错误后面显示红方块
s_username.innerHTML = "x";
s_username.className="error"
}
return flag;
}
//密码校验方法checkPassword
function checkPassword(){
//获取用户名的值
var password = document.getElementById("password").value;
//用正则表达式
var reg = /^\w{6,12}$/;
//判断值是否符合正则的规则
var flag = reg.test(password);
//提示信息
//获取span
var s_password = document.getElementById("s_password");
if(flag){
//提示正确后面绿色
s_password.innerText="y";
s_password.className="dui"
}else{
//提示错误后面显示红方块
s_password.innerHTML = "x";
s_password.className="error"
}
return flag;
}
</script>
<!--定义表单 -->
<form action="#" id="form" method="post">
<label form="username">用户名:</label>
<input type="text" name="username" id="username" placeholder="请输入用户名" />
<span id="s_username" ></span>
<label form="password">密码:</label>
<input type="password" name="password" id="password" placeholder="请输入密码" />
<span id="s_password" class="error"></span>
</form>