表单验证,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>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;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位数,离开焦点:

两次输入的密码不一致:

猜你喜欢

转载自blog.csdn.net/weixin_42044486/article/details/84065007
今日推荐