登陸表單驗證簡單實現

 
<!doctype html>
<html>
<head>
    <meta charset="UTF-8">
    <title>實現帶樣式的表單驗證
 </title>
    <style>
table{width:700px}
/*父元素下的第1個,第n個,最後一個td子元素*/td:first-child{width:60px}
/*IE不支持nth-child*/td:nth-child(2){width:200px}
/*IE*/td:first-child+td{width:200px}
/*IE不支持--能夠靠總寬度來調節 td:last-child{width:340px}*/td span{color:red}
        .vali_Info{/* 頁面初始,驗證消息不顯示*/display:none;}
        .txt_focus{border-top:2px solid black;border-left:2px solid black;}
        .vali_success,.vali_fail{background-repeat:no-repeat;background-position:left center;display:block;font-size:12px;}
/* 驗證消息:驗證經過時的樣式*/
 .vali_success{background-image:url("img/ok.png");padding-left:20px;width:0px;height:20px;overflow:hidden;}
/* 驗證消息:驗證失敗時的樣式*/
 .vali_fail{background-image:url("img/warning.png");border:1px solid red;background-color:#ddd;color:Red;padding-left:30px;}
    </style>
</head>
<body>
<form>
    <h2>增長管理員</h2>
    <table>
        <tr>
            <td >姓名:</td>
            <td><input name="userName"/>
                <span>*</span>
            </td>
            <td>
                <div class="vali_Info">
10個字符之內的字母、數字和下劃線的組合
 </div>
            </td>
        </tr>
        <tr>
            <td>密碼:</td>
            <td>
                <input type="password" name="pwd"/>
                <span>*</span>
            </td>
            <td>
                <div class="vali_Info">6位數字</div>
            </td>
        </tr>
        <tr>
            <td></td>
            <td colspan="2">
                <input type="submit" value="保存"/>
                <input type="reset" value="重填"/>
            </td>
        </tr>
    </table>
</form>
<script>
window.$=HTMLElement.prototype.$=function(selector){
return (this==window?document:this).querySelectorAll(selector);
    }

var form = document.forms[0];
var txtName =form.elements['userName'];
var txtPwd = form.elements['pwd'];

txtName.onfocus=txtPwd.onfocus = function(){
this.className="txt_focus";
this.parentNode.parentNode.$('div')[0].removeAttribute('class');    // div.className=""
 }

function valName(){
this.className="";
var div = this.parentNode.parentNode.$('div')[0];
var  r=/^\w{1,10}$/.test(this.value);
div.className = r?"vali_success":"vali_fail";
return r;
    }
function valPwd(){
this.className="";
var div = this.parentNode.parentNode.$('div')[0];
var reg = /^[0-9]{6}$/;
var r=reg.test(this.value)
div.className = r?"vali_success":"vali_fail";
return r;
    }
txtName.onblur=valName;
txtPwd.onblur=valPwd;
form.onsubmit = function(){
//都執行完,即便有報錯都顯示出來
//var  r = txtName.onblur()&txtPwd.onblur();
        //一個出錯後不執行
var  r = txtName.onblur()&&txtPwd.onblur();
if(!r){
var e  = window.event ||arguments[0];
if(e.preventDefault){
e.preventDefault();
            }else {
e.returnValue=false;
            }
        }else {
window.open('http://www.baidu.com')
        }
    }
</script>
</body>
</html>
 

相關文章
相關標籤/搜索