常用的一些校验
var Wi = [7, 9, 10, 5, 8, 4, 2, 1, 6, 3, 7, 9, 10, 5, 8, 4, 2, 1]; // 加权因子
var ValideCode = [1, 0, 10, 9, 8, 7, 6, 5, 4, 3, 2]; // 身份证验证位值.10代表X
// 查询条件级联操作
function provJoinCity(provinceCode, branchCode, url) {
var core=this;
$.ajax({
type : "post",// 使用post方法访问后台
dataType : "json",// 返回json格式的数据
url : url,// 要访问的后台地址
data : {
"provinceCode" : provinceCode.val()
},
success : function(data) {
if (data.code.key != core.code.SUCCESS) {
alert(data.code.message);
return;
}
data = data.result;
branchCode.empty();
branchCode
.append("<option value='' selected='selected'>---请选择---</option>");
$.each(data, function(i, item) {
branchCode
.append("<option value='"
+ item.code + "'>"
+ item.name
+ "</option>");
});
}
});
};
(function($) {
// 全局的ajax访问,处理ajax清求时sesion超时
$.ajaxSetup({
dataType : 'json',
error : function(xhr, status, e) {
if (xhr.status == 0) {
return true;
} else if (xhr.status == 493) {
window.location.href = '';
return false;
} else if (xhr.status == 425) {
alert(xhr.responseText);
return false;
} else {
alert("系统繁忙,请稍后再试!");
return false;
}
}
});
$.extend({
// 重置form
resetInsureInput : function(form) {
$(form).each(function() {
this.reset();
});
},
getBirthday : function(certNoObj, inputObj) {
var id = certNoObj.val();
if (id.length == 18) {
var birthday = id.substring(6, 10) + "-";
birthday += id.substring(10, 12) + "-";
birthday += id.substring(12, 14);
inputObj.val(birthday);
}
},
checkOneNull : function(myFields) {
$.each(myFields, function(i, n) {
if (n != "") {
confirm("页面有未保存数据,是否进入下一步?", function() {
$("#form_next").submit();
}, function() {
});
}
});
},
getSex : function(certNo, sexM, sexF) {
var certno = certNo.val();
if (certno.length == 18) {
var sex = certno.substring(16, 17);
if (sex % 2 == 0) {
sexF.attr("checked", "checked");
} else {
sexM.attr("checked", "checked");
}
}
},
idCard : function(idcardno) {
idcardno = trim(idcardno.replace(/ /g, "")); //去掉字符串头尾空格
if (idcardno.length == 18) {
var a_idCard = idcardno.split(""); // 得到身份证数组
if (isValidityBrithBy18IdCard(idcardno)
&& isTrueValidateCodeBy18IdCard(a_idCard)) { //进行18位身份证的基本验证和第18位的验证
return true;
} else {
return false;
}
} else {
return false;
}
}
});
window.alert = function(message, title, style, callback) {
if (top.location !== self.location
&& window.parent.document.body.nodeName.toUpperCase() == 'BODY') {
if ($("#dialog-message-alert", window.parent.document)) {
$("#dialog-message-alert", window.parent.document).remove();
}
} else {
if ($("#dialog-message-alert")) {
$("#dialog-message-alert").remove();
}
}
var dialogDiv = $('<div id="dialog-message-alert" style="display:none"></div>');
var dialogP = $('<p></p>');
dialogDiv.append(dialogP);
title = typeof(title) === 'undefined' || title == '' ? '温馨提示' : title;
dialogP.append(message);
if (top.location !== self.location
&& window.parent.document.body.nodeName.toUpperCase() == 'BODY') {
var b = $(window.parent.document.body);
b.prepend(dialogDiv);
$("#dialog-message-alert", window.parent.document).dialog({
modal : true,
autoOpen : false,
title : title,
resizable : false,
dialogClass : 'dialogClass',
minHeight : 200,
minWidth : 400,
closeOnEscape : true,
buttons : {
Ok : function() {
$(this).dialog("close");
if ($.isFunction(callback)) {
callback();
}
}
},
close : function() {
$(dialogDiv).remove();
if ($.isFunction(callback)) {
callback();
}
}
});
$("#dialog-message-alert", window.parent.document).dialog("open");
} else {
$("BODY").append(dialogDiv);
dialogDiv.dialog({
modal : true,
autoOpen : false,
title : title,
resizable : false,
dialogClass : 'dialogClass',
minHeight : 200,
minWidth : 400,
closeOnEscape : true,
buttons : {
确定: function() {
$(this).dialog("close");
if ($.isFunction(callback)) {
callback();
}
}
},
close : function() {
$(dialogDiv).remove();
if ($.isFunction(callback)) {
callback();
}
}
});
dialogDiv.dialog("open");
}
};
window.confirm = function(message, callback1, callback2, button1, button2) {
if ($("#dialog-message-confirm")) {
$("#dialog-message-confirm").remove();
}
var dialogDiv = $('<div id="dialog-message-confirm" style="display:none"></div>');
var dialogP = $('<p></p>');
dialogDiv.append(dialogP);
$("BODY").append(dialogDiv);
title = typeof(title) === 'undefined' || title == '' ? '温馨提示' : title;
button1 = typeof(button1) === 'undefined' || button1 == ''
? '确定'
: button1;
button2 = typeof(button2) === 'undefined' || button2 == ''
? '取消'
: button2;
$(dialogP).append(message);
$(dialogDiv).dialog({
modal : true,
autoOpen : false,
title : title,
resizable : false,
closeOnEscape : true,
dialogClass : 'dialogClass',
minHeight : 200,
minWidth : 360,
buttons : [{
text : button1,
click : function() {
$(this).dialog("close");
if ($.isFunction(callback1)) {
callback1();
}
}
}, {
text : button2,
click : function() {
$(this).dialog("close");
if ($.isFunction(callback2)) {
callback2();
}
}
}],
close : function() {
$(dialogDiv).remove();
}
});
$(dialogDiv).dialog("open");
};
$(window).scroll(function() {
if ($(window).scrollTop() > 76) {
if ($(".navbar-fixed-top").length == 0) {
$("#navbar")
.before("<div style='height: 40px;margin: 5px auto;' id='temp-navbar'></div>")
.addClass("navbar-fixed-top");
}
$("#goTop").show();
} else {
$("#goTop").hide();
$("#temp-navbar").remove();
$("#navbar").removeClass("navbar-fixed-top");
}
});
})(jQuery);
// 只允许中文和英文输入校验
jQuery.validator.addMethod("onlyCnAndEn", function(value, element) {
var tel = /^[a-zA-Z\u4e00-\u9fa5]+$/;
return this.optional(element) || (tel.test(value));
}, "请正确填写您的姓名");
/** 扩展validator验证类型*/
// 手机号码验证
jQuery.validator.addMethod("mobile", function(value, element) {
var length = value.length;
return this.optional(element)
|| (length == 11 && /^(((1[3|4|5|7|8][0-9]{1})|(15[0-9]{1})|(18[0-9]{1}))+\d{8})$/
.test(value));
}, "请输入正确格式的手机号码");
// 邮编验证
jQuery.validator.addMethod("zip", function(value, element) {
return this.optional(element) || (/^\d{6}$/.test(value));
}, "邮编号码格式不正确");
// 电话号码验证
jQuery.validator.addMethod("phone", function(value, element) {
return this.optional(element) || (/^(\d{4}|\d{3})-(\d{7,8})$/.test(value));
}, "请输入正确格式的电话号码");
// 国寿员工工号验证
jQuery.validator.addMethod("jobNo", function(value, element) {
return this.optional(element) || (/^\d{8}$/.test(value));
}, "请输入正确格式的员工工号");
//// 身份证号码验证
//jQuery.validator.addMethod("idcardno", function(value, element) {
// var length = value.length;
// return this.optional(element)
// || ((length == 18) && (/(^\d{15}$)|(^\d{17}([0-9]|X|x)$)/)
// .test(value));
//}, "请输入正确格式的身份证号码");
// 身份证号码验证
jQuery.validator.addMethod("idcardno", function(value, element) {
idcardno = trim(value.replace(/ /g, "")); //去掉字符串头尾空格
if (idcardno.length == 18) {
var a_idCard = idcardno.split(""); // 得到身份证数组
return this.optional(element)
|| (isValidityBrithBy18IdCard(idcardno) && isTrueValidateCodeBy18IdCard(a_idCard));
}
}, "请输入正确格式的身份证号码");
// 护照号码验证
jQuery.validator.addMethod("passport", function(value, element) {
var length = value.length;
var sport = /(P\d{7})|(G\d{8})/;
return this.optional(element) || (sport.test(value));
}, "请输入正确格式护照号码");
// 发票号码验证
jQuery.validator.addMethod("invoiceno", function(value, element) {
var length = value.length;
return this.optional(element) || (length == 8 && /^\d+$/.test(value));
}, "请输入正确格式的发票号码");
// IP地址验证
jQuery.validator.addMethod("ip", function(value, element) {
var ip = /^(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)$/;
return this.optional(element)
|| (ip.test(value) && (RegExp.$1 < 256 && RegExp.$2 < 256
&& RegExp.$3 < 256 && RegExp.$4 < 256));
}, "请输入正确格式的IP地址");
// MAC地址验证
jQuery.validator.addMethod("mac", function(value, element) {
var length = value.length;
var mac = /^[a-fA-F\d]{2}-[a-fA-F\d]{2}-[a-fA-F\d]{2}-[a-fA-F\d]{2}-[a-fA-F\d]{2}-[a-fA-F\d]{2}$/;
return this.optional(element) || (length == 17 && mac.test(value));
}, "请输入正确格式的MAC地址");
// 时间格式验证
jQuery.validator.addMethod("timeFormat", function(value, element) {
var length = value.length;
var timeformat = /^(\d{4})(-|\/)(\d{1,2})\2(\d{1,2}) (\d{1,2}):(\d{1,2}):(\d{1,2}).(\d{1,2})$/;
return this.optional(element) || (length == 21 && timeformat.test(value));
}, "请输入正确格式的时间(yyyy-mm-dd hh:mm:ss.f)"), jQuery.validator.addMethod(
"saleNoFormat", function(value, element) {
var length = value.length;
var saleNoFormat = /^\d{6}-\d{8}$/;
return this.optional(element)
|| (length == 15 && saleNoFormat.test(value));
}, "请输入正确格式的工号(000000-00000000)"),
// 邮政编码验证
jQuery.validator.addMethod("isZipCode", function(value, element) {
var tel = /^[0-9]{6}$/;
return this.optional(element) || (tel.test(value));
}, "请正确填写您的邮政编码");
var insuranceNo = /^[A-Za-z0-9]{22}$/;
// 保单号规则
jQuery.validator.addMethod("insuranceNo", function(value, element) {
return this.optional(element) || (insuranceNo.test(value));
}, "请填写正确的保单号");
// 银行卡号
jQuery.validator.addMethod("bankCardNo", function(value, element) {
return this.optional(element) || /^[0-9a-zA-Z]{16}$/.test(value)
|| /^[0-9a-zA-Z]{19}$/.test(value);
}, "请填写正确的银行卡号");
// 不等规则
jQuery.validator.addMethod("notEqualTo", function(value, element, param) {
var target = $(param).unbind(".validate-equalTo").bind(
"blur.validate-equalTo", function() {
$(element).valid();
});
return value != target.val();
});
// 非法字符校验
jQuery.validator.addMethod("chksafe", function(value, element) {
fibdn = new Array("'", "_", ">", "<", "*", "%", "#", "$", "}", "{", "~",
"`", "!", "¥", "/", "?", "&", "^", "。", ";", ":", ",", ".", "《",
"》", "【", "】", "(", ")");
i = fibdn.length;
j = value.length;
for (ii = 0; ii < i; ii++) {
for (jj = 0; jj < j; jj++) {
temp1 = value.charAt(jj);
temp2 = fibdn[ii];
if (temp1 == temp2) {
return false;
}
}
}
return true;
}, '请不要输入非法字符');
//针对企业名称过滤(部分字符)
jQuery.validator.addMethod("etpChksafe", function(value, element) {
fibdn = new Array("'", "_", ">", "<", "*", "%", "#", "$", "}", "{", "~",
"`", "!", "¥", "/", "?", "^", "。", ";", ":", ",", ".", "《",
"》", "【", "】");
i = fibdn.length;
j = value.length;
for (ii = 0; ii < i; ii++) {
for (jj = 0; jj < j; jj++) {
temp1 = value.charAt(jj);
temp2 = fibdn[ii];
if (temp1 == temp2) {
return false;
}
}
}
return true;
}, '请不要输入非法字符');
// 工号校验规则
jQuery.validator.addMethod("jobNumber", function(value, element) {
var tel = /^[0-9]{14}$/;
return this.optional(element) || (tel.test(value));
}, "请正确填写您的工号");
// 字节长度验证
jQuery.validator.addMethod("byteRangeLength", function(value, element, param) {
var length = value.length;
for (var i = 0; i < value.length; i++) {
if (value.charCodeAt(i) > 127) {
length++;
}
}
return this.optional(element) || (length <= (param * 2));
}, $.validator.format("请确保输入的值在{0}个字节之间(一个中文字算2个字节)"));
// 证件号码验证(仅数字+字母)
jQuery.validator.addMethod("certNo", function(value, element, param) {
return this.optional(element) || /^[a-zA-Z0-9_]+$/.test(value);
}, $.validator.format("请输入正确的证件号码"));
// 非数字验证
jQuery.validator.addMethod("noNumber", function(value, element, param) {
return this.optional(element) || !/^[0-9_]+$/.test(value);
}, $.validator.format("请不要输入数字"));
// 判断两个元素是否同时为空
jQuery.validator.addMethod("alternative", function(value, element, param) {
return jQuery(param).val() != '' || value != '';
}, "手机或邮箱必填一项");
// 根据一个元素不为空判断另一个也不能为空
jQuery.validator.addMethod("certTypeNull", function(value, element, param) {
if (jQuery(param).val() != '' && value == '') {
return false;
}
return true;
}, "证件号码不为空,证件类型不允许为空");
// 根据证件类型判断是否为必填项
jQuery.validator.addMethod("certTypeIdcard", function(value, element, param) {
if (jQuery(param).val() != 'I' && value == '') {
return false;
}
return true;
}, "请输入身份证号");
$.validator.addMethod("isNumberOrLetter", function(value, element) {
if (value != "") {
var score = new RegExp("^[A-Za-z0-9]+$");
return (score.test(value));
}
return true;
}, "请输入数字或字母");
$.validator.addMethod("noNumberOrParticular", function(value, element) {
var score = new RegExp("[`~!@#\\$%\\^&\\*\\(\\)_\\+-=,\\./<>\\?;:\'\"\\[\\]\\{\\}\\|\\\\0-9]+");
return !(score.test(value));
}, "不允许包含数字或特殊字符");
/** 设置日期选择插件的全局默认值*/
$.datepicker.setDefaults({
changeYear : true,
changeMonth : true,
dateFormat : "yy-mm-dd",
showOn : "both",
buttonText : "显示日期面板",
buttonImageOnly : true,
buttonImage : ""+dataBase+"/images/ui/calendar.gif",
dayNamesMin : ["日", "一", "二", "三", "四", "五", "六"],
monthNames : ["一月", "二月", "三月", "四月", "五月", "六月", "七月", "八月", "九月", "十月",
"十一月", "十二月"],
monthNamesShort : ["一月", "二月", "三月", "四月", "五月", "六月", "七月", "八月", "九月",
"十月", "十一月", "十二月"],
showAnim : "slideDown",
yearRange : "c-65:c",
maxDate : 0,
showButtonPanel : true,
closeText : "清空",
currentText : "今天"
});
/** 设置jqGrid插件的全局默认值*/
jQuery.extend(jQuery.jgrid.defaults, {
mtype : 'POST',
datatype : 'json',
rowNum : 10,
altRows : true,// 隔行变色
altclass : 'jqgrid-altclass',// 隔行变色样式
pager : "#tablePager",
multiselect : false,
viewrecords : true,
jsonReader : {
root : "dateList",
repeatitems : false
},
height : "auto",
autowidth : true,
hidegrid : false,// 禁用控制表格显示、隐藏的按钮
loadtext : "努力加载中.....",
rownumbers : true,
sortorder : "desc",
resizable : false
// true 列宽可调节,不过不知道为什么有没有这个属性,有时候都恩哪个调节列宽
});
/** 设置验证的默认值*/
$.validator.setDefaults({
errorClass : "validator-invalid",
onkeyup : false,// 是否在敲击键盘时验证
debug : false,
onfocusout : false,// 失去焦点是验证(不包括checkboxes/radio buttons)
focusInvalid : false,// 当验证无效时,焦点跳到第一个无效的表单元素。当为false时,验证无效时,没有焦点响应。
focusCleanup : true
// 当未通过验证的元素获得焦点时,并移除错误提示
});
// 将get请求转化为post请求
function get2post(_url, _target) {
var tempForm = document.createElement("FORM");
document.body.appendChild(tempForm);
tempForm.method = "POST";
var r = _url.indexOf('?');
if (r < 0) {
tempForm.action = _url;
} else {
tempForm.action = _url.slice(0, r);
_url = _url.slice(r + 1);
var params = _url.split('&');
for (var i = 0; i < params.length; i++) {
var s = params[i].split('=');
if (s[0] == "cmd") {
tempForm.action += "?cmd=" + s[1];
continue;
}
var new_input = document.createElement("input");
new_input.type = "hidden";
new_input.name = s[0];
new_input.value = s[1];
tempForm.appendChild(new_input);
}
}
if (_target) {
tempForm.target = _target;
}
tempForm.submit();
}
/**
* Jqgrid 单元格格式化函数
*
* @param {}
* cellvalue
* @param {}
* options
* @param {}
* rowObject
* @return {}
*/
var cellValueFormat = function nullFormat(cellvalue, options, rowObject) {
if (cellvalue == null || cellvalue == "") {// 如果为空返回"-"
return "-";
} else if (/^(\d{4})(-|\/)(\d{1,2})\2(\d{1,2}) (\d{1,2}):(\d{1,2}):(\d{1,2}).(\d{1,3})$/
.test($.trim(cellvalue))) {
// 如果为Timestamp则返回YYYY-MM-DD HH:MM:SS
return cellvalue.toString().substring(0, 10);
} else {// 其它则不进行改变
return cellvalue;
}
}
/**
* 验证18位数身份证号码中的生日是否是有效生日
* @param idCard 18位书身份证字符串
* @return
*/
function isValidityBrithBy18IdCard(idCard18) {
var year = idCard18.substring(6, 10);
var month = idCard18.substring(10, 12);
var day = idCard18.substring(12, 14);
var temp_date = new Date(year, parseFloat(month) - 1, parseFloat(day));
// 这里用getFullYear()获取年份,避免千年虫问题
if (temp_date.getFullYear() != parseFloat(year)
|| temp_date.getMonth() != parseFloat(month) - 1
|| temp_date.getDate() != parseFloat(day)) {
return false;
} else {
return true;
}
}
/**
* 判断身份证号码为18位时最后的验证位是否正确
* @param a_idCard 身份证号码数组
* @return
*/
function isTrueValidateCodeBy18IdCard(a_idCard) {
var sum = 0; // 声明加权求和变量
if (a_idCard[17].toLowerCase() == 'x') {
a_idCard[17] = 10; // 将最后位为x的验证码替换为10方便后续操作
}
for (var i = 0; i < 17; i++) {
sum += Wi[i] * a_idCard[i]; // 加权求和
}
valCodePosition = sum % 11; // 得到验证码所位置
if (a_idCard[17] == ValideCode[valCodePosition]) {
return true;
} else {
return false;
}
}
/*提取公共的异步请求*/
function query(id,url,postData){
var data='{'+postData+'"sessionId":"'+$("#variate").val()+'"}';
var cdata = eval("("+data+")");
id.setGridParam({
url :dataBase + url,
datatype : 'json',
page : 1,
postData : cdata
});
id.trigger("reloadGrid");
id.setGridWidth($('.jqgrid-table').width()* 1);
} $(document).ready(function() {
/*去掉输入框的空格*/
$("input").live("blur",function(){
if($(this).val()!="" && $(this).val()!=null){
if(/(^\s)|(\s$)/g.test($(this).val())==true){
if(/^\s/.test($(this).val())==true){
alert("您输入的内容包含空格,已将您输入的内容中的空格去掉,请注意查看!");
var vals=$(this).val().replace(/(^\s*)|(\s*$)/g,"");
$(this).val(vals);
}else if(/\s*$/g.test($(this).val())==true){
alert("您输入的内容包含空格,已将您输入的内容中的空格去掉,请注意查看!");
var vals=$(this).val().replace(/(^\s*)|(\s*$)/g,"");
$(this).val(vals);
}
};
};
});
});