方法一:
//验证封装函数
var g = function(id){return document.getElementById(id);}
var changed = function(id, fn){
g(id).onchange = fn;
}
var setNextHtml = function(id, html){
g(id).nextSibling.innerHTML = html;
}
var val = function(id){
return g(id).value;
}
//QQ验证
changed('inp1', function(){
if(/^\d{5,11}$/.test(val('inp1'))){
setNextHtml('inp1', '');
}else{
setNextHtml('inp1', '请输入5到11位数字');
}
});
//手机号验证
changed('inp2', function(){
if(/^1\d{10}$/.test(val('inp2'))){
setNextHtml('inp2', '');
}else{
setNextHtml('inp2', '数字1开头,11位的数字');
}
});
//用户名验证
changed('inp3', function(){
if(/^[\w\-\u4e00-\u9fa5]{1,7}$/.test(val('inp3'))){
setNextHtml('inp3', '')
}else{
setNextHtml('inp3', '1到7位')
}
});
//密码验证
changed('inp4', function(){
if(/^[A-Z]\w{1,15}$/.test(val('inp4'))){
setNextHtml('inp4', '');
}else{
setNextHtml('inp4', '首字母大写,1到16位');
}
});
//邮箱验证
changed('inp5', function(){
if(/^[\w\-\.]+\@[\w]+\.[\w]{2,4}/.test(val('inp5'))){
setNextHtml('inp5', '')
}else{
setNextHtml('inp5', '请输入正确邮箱格式')
}
});
方法二:
//获取元素就不说明了^_^
//正则表达式
var regObj = {
"regQQ" : /^\d{5,12}$/,
"regMail" : /^\w+@\w+\.\w+(\.\w+)?$/,
"regPhone" : /^\d{11}$/,
"regBirthday" : /^\d{4}-\d{1,2}-\d{1,2}$/,
"regName" : /^[\u4e00-\u9fa5]{2,4}$/
}
var inputs = document.getElementsByTagName("input");
for(var i=0; i<input.length;i++){
var input=input[i];
if(input.type == "text"){
var reg = input.id.replace("txt","reg");
var tip = input.previousElementSibling.innerText;
tip = "请输入正确的" + tip.substr(0,tip.length-1);
addCheck(input, regObj[reg], tip);
}
}
//给文本框添加验证
function addCheck(element, reg, tip) {
element.onblur = function () {
//获取当前文本框对应的span
var span = this.nextElementSibling;
//判断验证是否成功
if(!reg.test(this.value) ){
//验证不成功
span.innerText = tip;
span.style.color = "red";
}else{
//验证成功
span.innerText = "";
span.style.color = "";
}
};
}