最近准备把公司开发的CMS的表单添加中增加客户端的表单验证,之前一直是使用的ASP.NET自带的服务器验证控件,其用起来固然方便,但却无形中也给服务器带来了压力。
(function ($) {
var FormValidator = function () {
this.regexEnum = {
idCard: /^[1-9]([0-9]{14}|[0-9]{16})([0-9]|X)$/,
num: /^\-?([1-9]\d*)$/, //数字
email: /^([0-9A-Za-z\-_\.]+)@([0-9a-z]+\.[a-z]{2,3}(\.[a-z]{2})?)$/,
phone: /^1[3|4|5|8]\d{9}$/
};
this.validatorArr = {};
};
FormValidator.prototype.init = function () {
var scope = this;
$(\'.formValidate\').each(function () {
var el = $(this);
scope.initItem(el);
}); //each
};
FormValidator.prototype.initItem = function (el) {
var scope = this;
var cfg = el.attr(\'data-cfg\');
if (cfg && cfg.length > 0) {
cfg = eval(\'(\' + cfg + \')\');
// cfg = JSON.parse(cfg);
var check = cfg.check || true,
id = el.attr(\'id\') || new Date().getTime(),
initMsg = cfg.initMsg || \'请填入信息\',
sucMsg = cfg.sucMsg || \'格式正确\',
errorMsg = cfg.errorMsg || \'请注意格式\',
type = cfg.type || \'\',
requred = cfg.requred || false,
msgPosition = cfg.msgPosition || \'right\';
cfg.id = id;
cfg.initMsg = initMsg;
cfg.sucMsg = sucMsg;
cfg.errorMsg = errorMsg;
cfg.type = type;
cfg.msgPosition = msgPosition;
cfg.requred = requred;
cfg.requredMsg = cfg.requredMsg || \'该项必填\';
if (check) {
var tips = $(\'<div class="validateTips validateInit" id="\' + id + \'Tips"><div class="triangle_icon"><div class="before"></div><div class="after"></div></div>\' + initMsg + \'</div>\');
// var tips = $(\'<div class="validateTips validateInit" id="\' + id + \'Tips">\' + initMsg + \'</div>\');
var offset = el.offset();
var height = parseInt(el.outerHeight());
var width = parseInt(el.outerWidth());
var l = offset.left;
var t = offset.top;
if (msgPosition == \'bottom\') {
tips.addClass(\'posBottom\');
t += height + 4;
} else if (msgPosition == \'right\') {
tips.addClass(\'posRight\');
l += width + 6;
} else if (msgPosition == \'top\') {
tips.addClass(\'posTop\');
t += height * ( -1) - 8;
}
tips.css({ left: l, top: t });
$(\'body\').append(tips);
cfg.el = el;
cfg.tipEl = tips;
el.focus(function () {
scope.funcValidate(el, cfg);
});
el.blur(function () {
scope.funcValidate(el, cfg);
});
el.keyup(function () {
scope.funcValidate(el, cfg);
});
el.keydown(function () {
scope.funcValidate(el, cfg);
});
cfg.validate = function () {
scope.funcValidate(el, cfg);
};
scope.validatorArr[id] = cfg; //生成相关验证对象
}
} else {
console.log(\'请输入完整验证信息!否则控件会产生错误!\');
}
};
FormValidator.prototype.funcValidate = function (el, cfg) {
var id = cfg.id;
//取消事件不执行下面逻辑
if (!this.validatorArr[id])
return false;
var type = cfg.type;
var requred = cfg.requred;
if (!type && !this.regexEnum[type]) {
return false;
}
var isPass = 0; //0初始状态,1成功,-1错误
var msg = \'\';
var r = this.regexEnum[type] ? this.regexEnum[type] : type;
if (requred && el.val() == \'\') {
isPass = -1;
msg = cfg.requredMsg;
} else {
if (el.val() == \'\') {
isPass = 0;
msg = cfg.initMsg;
} else {
if (r.test(el.val())) {
isPass = 1;
msg = cfg.sucMsg;
} else {
isPass = -1;
msg = cfg.errorMsg;
}
}
}
if (isPass == 0) {
this.validatorArr[id][\'tipEl\'].removeClass(\'validateError\');
this.validatorArr[id][\'tipEl\'].removeClass(\'validateSuc\');
this.validatorArr[id][\'tipEl\'].addClass(\'validateInit\');
this.validatorArr[id][\'tipEl\'].html(\'<div class="triangle_icon"><div class="before"></div><div class="after"></div></div>\' + msg);
} else if (isPass == 1) {
this.validatorArr[id][\'state\'] = \'success\';
this.validatorArr[id][\'tipEl\'].removeClass(\'validateError\');
this.validatorArr[id][\'tipEl\'].removeClass(\'validateInit\');
this.validatorArr[id][\'tipEl\'].addClass(\'validateSuc\');
this.validatorArr[id][\'tipEl\'].html(\'<div class="triangle_icon"><div class="before"></div><div class="after"></div></div>\' + msg);
} else if (isPass == -1) {
this.validatorArr[id][\'state\'] = \'error\';
this.validatorArr[id][\'tipEl\'].removeClass(\'validateSuc\');
this.validatorArr[id][\'tipEl\'].removeClass(\'validateInit\');
this.validatorArr[id][\'tipEl\'].addClass(\'validateError\');
this.validatorArr[id][\'tipEl\'].html(\'<div class="triangle_icon"><div class="before"></div><div class="after"></div></div>\' + msg);
}
};
FormValidator.prototype.validatorAll = function () {
for (var k in this.validatorArr) {
var v = this.validatorArr[k];
v.validate();
}
};
FormValidator.prototype.removeValidator = function (id) {
if (id && this.validatorArr[id]) {
// this.validatorArr[id].tipEl
this.validatorArr[id].tipEl.remove(); //删除提示信息
delete this.validatorArr[id]; //删除该验证项目
// this.validatorArr[id].el.unbind();//移除所有事件,但是考虑标签可能会有其他事件,此处暂时不予处理
var s = \'\';
}
};
FormValidator.prototype.addValidator = function (id) {
var el = $(\'#\' + id);
this.initItem(el);
};
FormValidator.prototype.validatorState = function () {
for (var k in this.validatorArr) {
var v = this.validatorArr[k];
if (v.state == \'error\') {
return false;
}
}
return true;
};
window.FormValidator = FormValidator;
})(jQuery);
View Code
配合html代码
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title></title>
<style type="text/css">
.form div { height: 30px; line-height: 30px; margin: 5px; }
.validateTips { min-width: 100px; border-radius: 2px; padding: 5px 10px; z-index: 500; position: absolute; font-size: 12px; }
.validateInit { background: #FFFFE0; border: 1px solid #F7CE39; }
.validateError { background: orange; border: 1px solid red; }
.validateSuc { background: #79D62D; border: 1px solid Green; }
.triangle_icon { position: absolute; }
.triangle_icon div { border-style: solid; border-width: 6px; position: absolute; }
/*上边提示*/
.posTop .triangle_icon { width: 12px; height: 12px; bottom: -12px; }
.posTop .triangle_icon .after { bottom: 1px; }
.posTop .triangle_icon .after { border-bottom-color: transparent; border-right-color: transparent; border-left-color: transparent; }
.posTop .triangle_icon .before { border-bottom-color: transparent; border-right-color: transparent; border-left-color: transparent; }
/*右边提示*/
.posRight .triangle_icon { width: 12px; height: 12px; left: -12px; }
.posRight .triangle_icon .after { left: 1px; }
.posRight .triangle_icon .after { border-top-color: transparent; border-bottom-color: transparent; border-left-color: transparent; }
.posRight .triangle_icon .before { border-top-color: transparent; border-bottom-color: transparent; border-left-color: transparent; }
/*下边提示*/
.posBottom .triangle_icon { width: 12px; height: 12px; top: -12px; }
.posBottom .triangle_icon .after { top: 1px; }
.posBottom .triangle_icon .after { border-top-color: transparent; border-right-color: transparent; border-left-color: transparent; }
.posBottom .triangle_icon .before { border-top-color: transparent; border-right-color: transparent; border-left-color: transparent; }
/*初始化时候的皮肤*/
.validateInit .before { border-color: #F7CE39; }
.validateInit .after { border-color: #FFFFE0; }
/*失败时候的皮肤*/
.validateError .before { border-color: red; }
.validateError .after { border-color: orange; }
/*成功时候的皮肤*/
.validateSuc .before { border-color: Green; }
.validateSuc .after { border-color: #79D62D; }
</style>
<script src="js/jquery-1.7.1.min.js" type="text/javascript"></script>
<script src="js/yexiaochai_formValidator.js" type="text/javascript"></script>
<script type="text/javascript">
$(document).ready(function () {
var f = new FormValidator();
f.init();
f.validatorAll();
var bt = $(\'#bt\');
var add = $(\'#add\');
var remove = $(\'#remove\');
var name = $(\'#name\');
bt.click(function () {
var end = f.validatorState();
var s = \'\';
});
add.click(function () {
f.addValidator(name.val());
var s = \'\';
});
remove.click(function () {
f.removeValidator(name.val());
var s = \'\';
});
});
</script>
</head>
<body>
<input type="text" id="name" />
<input type="button" value="取消验证" id="remove" />
<input type="button" value="添加验证" id="add" />
<div class="form">
<div>
身份证:<input type="text" id="idCard" class="formValidate" data-cfg="{ check: \'true\', type: \'idCard\', msgPosition: \'right\', initMsg: \'请输入身份证号码!\', requred: true, sucMsg: \'正确\', errorMsg: \'格式错误\'}" />
</div>
<div>
数字:<input type="text" id="num" class="formValidate" data-cfg="{ type: \'num\', initMsg: \'请输入数字\', msgPosition: \'top\'}" />
</div>
<div>
邮件:<input type="text" class="formValidate" data-cfg="{ type: \'email\', initMsg: \'请输入邮箱地址!\'}" />
</div>
<div>
手机:<input type="text" class="formValidate" data-cfg="{ type: \'phone\', initMsg: \'请请输入手机号码!\'}" />
</div>
<div>
QQ:<input type="text" class="formValidate" data-cfg="{ type: /^[1-9]*[1-9][0-9]*$/, initMsg: \'请请输入手机号码!\'}" />
</div>
<div>
用户名:<input type="text" />
</div>
<div>
密码:<input type="text" />
</div>
<div>
重复密码:<input type="text" />
</div>
<div>
性别:
<label>
<input type="radio" name="Gender" value="0" />
男</label>
<label>
<input type="radio" name="Gender" value="1" />
女</label>
</div>
<div>
爱好:
<label>
<input type="checkbox" name="aihao" value="0" />
爱好1</label>
<label>
<input type="checkbox" name="aihao" value="1" />
爱好2</label>
<label>
<input type="checkbox" name="aihao" value="0" />
爱好3</label>
<label>
<input type="checkbox" name="aihao" value="1" />
爱好4</label>
</div>
<input type="button" value="提交" id="bt" />
</div>
</body>
</html>
View Code
这个demo中涉及到了挺多js验证代码!