验证的js代码
/// <reference path="jquery-1.7.1.min.js" />
(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}$/,
chinese: /^[\u0391-\uFFE5]{2,6}$/, //2-6位中文
password: /^[a-zA-Z0-9_]{8,32}$/ //6-32位密码验证
};
this.validatorArr = {};
};
FormValidator.prototype.requred = function (el) {
// if (el.val() == '') {
// return false;
// }
return true;
}
FormValidator.prototype.init = function () {
var scope = this;
$('.formValidate').each(function () {
var el = $(this);
scope.initItem(el);
}); //each
};
FormValidator.prototype.initItem = function (el) {
if (typeof el == 'string') el = $('#' + 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 || '请注意格式',
requred = cfg.requred || false,
msgPosition = cfg.msgPosition || 'right';
cfg.id = id;
cfg.check = check;
cfg.initMsg = initMsg;
cfg.sucMsg = sucMsg;
cfg.errorMsg = errorMsg;
cfg.msgPosition = msgPosition;
cfg.requred = requred;
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;
//该表单的验证
cfg.validate = function () {
scope.funcValidate(el, cfg);
};
//会触发验证的事件(取消验证后,该事件取消的话害怕引起事件丢失)
el.change(function () {
scope.funcValidate(el, cfg);
});
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);
});
scope.validatorArr[id] = cfg; //生成相关验证对象
} else {
console.log('请输入完整验证信息!否则控件会产生错误!');
}
};
FormValidator.prototype.funcValidate = function (el, cfg) {
var id = cfg.id;
var check = cfg.check; //判断是否开启验证
//取消事件不执行下面逻辑
if (!this.validatorArr[id])
return false;
//若是没有开启验证便忽略之
if (!check) {
this.validatorArr[id]['state'] = 'ignore';
return false;
}
var type = cfg.type;
var regexObj = cfg.regexObj; //正则相关
var rangeObj = cfg.rangeObj; //范围验证
var compareObj = cfg.compareObj; //范围验证
var msg = '';
var isPass = 1; //1成功,-1错误
//首先进行非空验证
if (cfg.requred) {
if (el.val() == '') {
isPass = -1;
msg = '该项必填';
}
}
//type优先
if (isPass == 1 && el.val().length > 0 && typeof type == 'string') {
var typeArr = type.split('|'); //可能包含验证组
var errorArr = cfg.errorMsg.split('|'); //各个组错误时候对应的信息
for (var i = 0, len = typeArr.length; i < len; i++) {
var r = this.regexEnum[typeArr[i]];
//测试通过
if (r.test(el.val())) {
msg = cfg.sucMsg;
} else {
isPass = -1;
msg = errorArr[i] ? errorArr[i] : cfg.errorMsg;
break; //一旦有错误的地方便中断
}
}
}
//当第一步验证通过便执行自身正则验证
if (isPass == 1 && el.val().length > 0 && regexObj) {
//当未指定type时候,便执行页面中的正则表达式对象
var r = regexObj;
if (r.test(el.val())) {
msg = cfg.sucMsg;
} else {
isPass = -1;
msg = cfg.errorMsg;
}
}
//当第二步验证通过便执行范围验证
if (isPass == 1 && el.val().length > 0 && rangeObj) {
//日期验证暂时忽略
var rangeArr = rangeObj.split('|');
if (rangeArr.length == 3) {
var _v = el.val();
var _p1 = rangeArr[1];
var _p2 = rangeArr[2];
if (rangeArr[0] == 'num') {
_v = parseInt(el.val());
_p1 = parseInt(rangeArr[1]);
_p2 = parseInt(rangeArr[2]);
}
if (_v > _p1 && _v < _p2) {
msg = cfg.sucMsg;
} else {
isPass = -1;
msg = '请填入' + rangeArr[0] + '到' + rangeArr[1] + '直接的数字';
}
} else {
console.log('范围参数错误');
}
}
//执行对比运算
if (isPass == 1 && el.val().length > 0 && compareObj) {
var compareArr = compareObj.split('|');
if (compareArr.length == 3) {
var _type = compareArr[0]
var _id = compareArr[1];
var _flag = compareArr[2];
var _v = el.val();
var _cv = $('#' + _id).val();
if (_type == 'num') {
_v = parseInt(_v);
_cv = parseInt(_cv);
}
if (_flag == '<') {
if (_v < _cv) {
msg = cfg.sucMsg;
} else {
isPass = -1;
msg = '该值过大';
}
}
if (_flag == '>') {
if (_v > _cv) {
msg = cfg.sucMsg;
} else {
isPass = -1;
msg = '该值过小';
}
}
if (_flag == '=') {
if (_v == _cv) {
msg = cfg.sucMsg;
} else {
isPass = -1;
msg = '两次数据不一致';
}
}
} else {
console.log('范围参数错误');
}
}
if (msg == '') isPass = 0;
if (isPass == 0) {
this.validatorArr[id]['state'] = 'init';
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>' + cfg.initMsg);
} 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.remove(); //删除提示信息
this.validatorArr[id]['check'] = false; //将其验证状态置为false
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; }
/*表单相关样式,和验证无关,可删除*/
.form { width: 820px; margin: 0 auto; }
.form ul { list-style-type: none; padding-left: 0; }
.form li > label { display: inline-block; min-width: 200px; padding-right: 14px; text-align: right; vertical-align: -2px; }
.form ul .text { display: inline-block; line-height: 40px; margin-left: 10px; }
/*表单相关样式,和验证无关,可删除*/
</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');
var single = $('#single');
bt.click(function () {
f.validatorAll();
var end = f.validatorState();
var s = '';
});
single.click(function () {
f.initItem(name.val());
var s = '';
});
add.click(function () {
f.addValidator(name.val());
var s = '';
});
remove.click(function () {
f.removeValidator(name.val());
var s = '';
});
});
</script>
</head>
<body>
<div class="form">
<input type="text" id="name" />
<input type="button" value="取消验证" id="remove" />
<input type="button" value="添加验证" id="add" />
<input type="button" value="单项验证" id="single" />
<ul>
<li>
<label>
身份证:</label>
<div class="text">
<input type="text" id="idCard" class="formValidate" data-cfg="{ requred: true, type: 'idCard', msgPosition: 'right', initMsg: '请输入身份证号码!', sucMsg: '正确', errorMsg: '该项必填|格式错误'}" />
</div>
</li>
<li>
<label>
数字:
</label>
<div class="text">
<input type="text" id="num" class="formValidate" data-cfg="{ type: 'num'}" />
</div>
</li>
<li>
<label>
邮件:
</label>
<div class="text">
<input type="text" class="formValidate" data-cfg="{ type: 'email', initMsg: '请输入邮箱地址!'}" />
</div>
</li>
<li>
<label>
手机:
</label>
<div class="text">
<input type="text" class="formValidate" data-cfg="{ type: 'phone', initMsg: '请请输入手机号码!'}" />
</div>
</li>
<li>
<label>
QQ:
</label>
<div class="text">
<input type="text" class="formValidate" data-cfg="{ regexObj: /^[1-9]*[1-9][0-9]*$/, initMsg: '请请输入手机号码!'}" />
</div>
</li>
<li>
<label>
年龄要求(18-25):
</label>
<div class="text">
<input type="text" class="formValidate" data-cfg="{ rangeObj: 'num|18|25', initMsg: '请输入您的年龄'}" />
</div>
</li>
<li>
<label>
用户名:
</label>
<div class="text">
<input type="text" class="formValidate" />(ajax类型测试)
</div>
</li>
<li>
<label>
密码:
</label>
<div class="text">
<input type="text" id="pwd" class="formValidate" data-cfg="{ requred: true, type: 'password', msgPosition: 'right', initMsg: '请输入密码!', sucMsg: '正确', errorMsg: '格式错误'}" />
</div>
</li>
<li>
<label>
重复密码:
</label>
<div class="text">
<input type="text" id="rePwd" class="formValidate" data-cfg="{ compareObj: 'str|pwd|=', requred: true}" />(验证对比时,应该考虑日期,字符串,数字)
</div>
</li>
<li>
<label>
工作年限/薪水范围:
</label>
<div class="text">
<input type="text" id="d_start" class="formValidate" data-cfg="{ type: 'num', msgPosition: 'bottom' }" />-
<input type="text" id="d_end" class="formValidate" data-cfg="{ compareObj: 'num|d_start|>', type: 'num', msgPosition: 'bottom' }" />
</div>
</li>
<li>
<br />
<br />
<label>
学历:
</label>
<div class="text">
<select id="sec" class="formValidate" data-cfg="{ requred: true, initMsg: '请选择学历!', sucMsg: '正确', errorMsg: '必须选择学历' }">
<option value="" selected="selected">请选择</option>
<option value="1">专科</option>
<option value="2">本科</option>
<option value="3">硕士</option>
</select>
</div>
</li>
</ul>
<input type="button" value="提交" id="bt" />
</div>
</body>
</html>
View Code
浙公网安备 33010602011771号