QQ号:<input type="text" id="txtQQ"><span></span><br>
邮箱:<input type="text" id="txtEMail"><span></span><br>
手机:<input type="text" id="txtPhone"><span></span><br>
生日:<input type="text" id="txtBirthday"><span></span><br>
姓名:<input type="text" id="txtName"><span></span><br>
//1.获取页面所有的inputs
var inputs = my$byTagName("input");
//2.遍历inputs绑定事件
for(var i=0;i<inputs.length;i++){
inputs[i].onblur = function(){
checkCorrect(this);
}
}
//3.每次文本框失去焦点时候确定文本框对应的正则以及提示
function checkCorrect(ele){
var reg = null;
var tip = null;
//检验QQ
if(ele.getAttribute("name") == "qq") {
reg = /^[1-9]\d{4,10}$/;
tip = "请输入正确的QQ号码";
}
//校验email
else if(ele.getAttribute("name") == "email"){
reg = /^\w+@\w+\.\w+(\.\w+)?$/;
tip = "请输入正确的email";
}
else if(ele.getAttribute("name") == "phone"){
reg = /^1[34578]\d{9}$/;
tip = "请输入正确的手机号码";
}
else if(ele.getAttribute("name") == "birthday"){
reg = /^((\d{4})-(\d{2})-(\d{2}))$/;
tip = "请输入正确的生日";
}
else if(ele.getAttribute("name") == "name"){
reg = /^\w{2,}$/;
tip = "请输入正确的名字";
}
//真正去进行校验
doCheck(ele,reg,tip);
}
//正则的校验
function doCheck(element, reg, tip){
//获取当前input的下一个兄弟元素
var span = element.nextElementSibling;
//如果正则校验通过,则输入正确
if(reg.test(element.value)){
span.style.color = "green";
setInnerText(span,"输入正确");
}
else{
span.style.color = "red";
setInnerText(span,tip);
}
}