表單驗證,onfocus,onblur事件
<!DOCTYPE html>
<html lang="zh">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<meta http-equiv="X-UA-Compatible" content="ie=edge" />
<title>Document</title>
<script>
function focusObj(id){
id.style.backgroundColor="#FFCC80";
}
//驗證郵箱
function blurObjd(id){
if(id.value.indexOf("@")==-1){
document.getElementById("reEmail").innerHTML="Email不合法,沒有包含@符合!";
id.focus();
}else{
document.getElementById("reEmail").innerHTML="";
}
}
//驗證密碼
function blurPass(id){
if(id.value.length<6){
document.getElementById("rePassword").innerHTML="密碼不能少於6位數";
id.focus();
}else{
document.getElementById("rePassword").innerHTML="";
}
}
//驗證密碼是否一致
function blurRepass(id){
var password = document.getElementById("password").value;
if(id.value!=password){
document.getElementById("repass").innerHTML="兩次密碼不一致!";
id.focus();
}else{
document.getElementById("repass").innerHTML="";
}
}
</script>
</head>
<body>
<form action="#" method="post">
<table>
<tr>
<td> email:<input type="text" id="email" onfocus="focusObj(this)"
onblur="blurObjd(this)"/></td>
<td><div id="reEmail"></div></td>
</tr>
<tr>
<td>輸入密碼:<input type="password" id="password" onfocus="focusObj(this)"
onblur="blurPass(this)"/></td>
<td><div id="rePassword"></div></td>
</tr>
<tr>
<td>確認密碼:<input type="password" id="pass" onfocus="focusObj(this)"
onblur="blurRepass(this)"/></td>
<td><div id="repass"></div></td>
</tr>
</table>
</form>
</body>
</html>
未驗證時:
點選文字框時背景顏色改變:
輸入不合法的email地址,然後點選下一個文字框(離開焦點):
輸入正確的email(只驗證了@符合),離開焦點:
輸入的密碼少於6位數,離開焦點:
兩次輸入的密碼不一致: