2008年9月26日 星期五

jQuery的身份證驗證plugin

/**
* 驗證身份證字號是否正確的jquery plugin
* 用法:jQuery('身份證字號的id').idCheck();
* 傳回值:
* 合法---傳回true
* 非法---傳回false
* 作者:羅仁治
* 版本:1.0
* 版權:隨你使用,但須保留這段說明文字。
*/
jQuery.fn.idCheck = function(){
var real_id = this.val();
real_id = real_id.toUpperCase();


var pattern = /^[A-Z]{1}[0-9]{9}$/;
if (!pattern.test(real_id)) {
return false;
}

if (check(real_id)) {
return true;
}
else {
return false;
}


function check(real_id){
var first = real_id.substr(0, 1);
switch (first) {
case 'A':
first = '10';
break;
case 'B':
first = '11';
break;
case 'C':
first = '12';
break;
case 'D':
first = '13';
break;
case 'E':
first = '14';
break;
case 'F':
first = '15';
break;
case 'G':
first = '16';
break;
case 'H':
first = '17';
break;
case 'I':
first = '34';
break;
case 'J':
first = '18';
break;
case 'K':
first = '19';
break;
case 'L':
first = '20';
break;
case 'M':
first = '21';
break;
case 'N':
first = '22';
break;
case 'O':
first = '35';
break;
case 'P':
first = '23';
break;
case 'Q':
first = '24';
break;
case 'R':
first = '25';
break;
case 'S':
first = '26';
break;
case 'T':
first = '27';
break;
case 'U':
first = '28';
break;
case 'V':
first = '29';
break;
case 'W':
first = '32';
break;
case 'X':
first = '30';
break;
case 'Y':
first = '31';
break;
case 'Z':
first = '33';
break;
}

var value = first.concat(real_id.substr(1, 8));

var sum = parseInt(value.substr(0, 1));

for (var i = 1; i <= 9; i++) {
sum = sum + parseInt(value.substr(i, 1)) * (10 - i);
}

single = 10 - (sum % 10);

if (parseInt(real_id.substr(9, 1)) == single) {
return true;
}
else {
return false;
}
}
};

沒有留言: