jquery validate自定义验证方法(转)
// 身份证号码验证
jQuery.validator.addMethod("idcardno",function(value,element){
returnthis.optional(element)||isIdCardNo(value);
},"请正确输入身份证号码");
//字母数字
jQuery.validator.addMethod("alnum",function(value,element){
returnthis.optional(element)||/^[a-zA-Z0-9]+$/.test(value);
},"只能包括英文字母和数字");
//手机号码验证
jQuery.validator.addMethod("cellphone",function(value,element){
varlength=value.length;
returnthis.optional(element)||(length==11&&/^(1\d{10})$/.test(value));
},"请正确填写手机号码");
//电话号码验证
jQuery.validator.addMethod("telephone",function(value,element){
vartel=/^(\d{3,4}-?)?\d{7,9}$/g;
returnthis.optional(element)||(tel.test(value));
},"请正确填写电话号码");
//邮政编码验证
jQuery.validator.addMethod("zipcode",function(value,element){
vartel=/^[0-9]{6}$/;
returnthis.optional(element)||(tel.test(value));
},"请正确填写邮政编码");
//汉字
jQuery.validator.addMethod("chcharacter",function(value,element){
vartel=/^[\u4e00-\u9fa5]+$/;
returnthis.optional(element)||(tel.test(value));
},"请输入汉字");
functionisIdCardNo(num){
varfactorArr=newArray(7,9,10,5,8,4,2,1,6,3,7,9,10,5,8,4,2,1);
varparityBit=newArray("1","0","X","9","8","7","6","5","4","3","2");
varvarArray=newArray();
varintValue;
varlngProduct=0;
varintCheckDigit;
varintStrLen=num.length;
varidNumber=num;
//initialize
if((intStrLen!=15)&&(intStrLen!=18)){
returnfalse;
}
//checkandsetvalue
for(i=0;i<intStrLen;i++){
varArray[i]=idNumber.charAt(i);
if((varArray[i]<'0'||varArray[i]>'9')&&(i!=17)){
returnfalse;
}elseif(i<17){
varArray[i]=varArray[i]*factorArr[i];
}
}
if(intStrLen==18){
//checkdate
vardate8=idNumber.substring(6,14);
if(isDate8(date8)==false){
returnfalse;
}
//calculatethesumoftheproducts
for(i=0;i<17;i++){
lngProduct=lngProduct+varArray[i];
}
//calculatethecheckdigit
intCheckDigit=parityBit[lngProduct%11];
//checklastdigit
if(varArray[17]!=intCheckDigit){
returnfalse;
}
}
else{//lengthis15
//checkdate
vardate6=idNumber.substring(6,12);
if(isDate6(date6)==false){
returnfalse;
}
}
returntrue;
}
functionisDate6(sDate){
if(!/^[0-9]{6}$/.test(sDate)){
returnfalse;
}
varyear,month,day;
year=sDate.substring(0,4);
month=sDate.substring(4,6);
if(year<1700||year>2500)returnfalse
if(month<1||month>12)returnfalse
returntrue
}
functionisDate8(sDate){
if(!/^[0-9]{8}$/.test(sDate)){
returnfalse;
}
varyear,month,day;
year=sDate.substring(0,4);
month=sDate.substring(4,6);
day=sDate.substring(6,8);
variaMonthDays=[31,28,31,30,31,30,31,31,30,31,30,31]
if(year<1700||year>2500)returnfalse
if(((year%4==0)&&(year%100!=0))||(year%400==0))iaMonthDays[1]=29;
if(month<1||month>12)returnfalse
if(day<1||day>iaMonthDays[month-1])returnfalse
returntrue
}