正規表達式:主要是用來比對字元串的。
- html部分
<div class="container" id="dv">
<!-- label标簽的作用是點選QQ或者手機字的時候,光标自動到文本框裡-->
<label for="qq">Q Q</label><input type="text" id="qq"><span></span><br/>
<label for="phone">手機</label><input type="text" id="phone"><span></span><br/>
<label for="e-mail">郵箱</label><input type="text" id="e-mail"><span></span><br/>
<label for="telephone">座機</label><input type="text" id="telephone"><span></span><br/>
<label for="fullName">姓名</label><input type="text" id="fullName"><span></span><br/>
</div>
- css部分
body {
background: #ccc;
}
label {
width: 40px;
display: inline-block;
}
span {
color: red;
}
.container {
margin: 100px auto;
width: 400px;
padding: 50px;
line-height: 40px;
border: 1px solid #999;
background: #efefef;
}
span {
margin-left: 30px;
font-size: 12px;
}
.wrong {
color: red
}
.right {
color: green;
}
.defau {
width: 200px;
height: 20px;
}
.de1 {
background-position: 0 -20px;
}
- js部分
//擷取每個input标簽,調用函數。
checkValue(my$("qq"), /^\d{5,10}$/);
checkValue(my$("phone"), /^\d{11}$/);
checkValue(my$("e-mail"), /^[0-9a-zA-Z_.-]+[@][0-9a-zA-Z_.-]+([.][a-zA-Z]+){1,2}$/);
checkValue(my$("telephone"), /^[0-9]{3,4}[-][0-9]{6}$/);
checkValue(my$("fullName"), /^[\u4e00-\u9fa5]{2,6}$/);
//把輸入input裡的值拿來與對應的正規表達式作比較
function checkValue(input, reg) {
input.onblur = function () {
if (reg.test(this.value)) {
this.nextElementSibling.innerHTML = "正确";
this.nextElementSibling.className = "right";
} else {
this.nextElementSibling.innerHTML = "請輸入正确的格式";
this.nextElementSibling.className = "wrong";
}
};
}