// js版校验
var IdCardValid = {//身份证检查
isIdCard : function(_id) {
var returnObj = new Object();
var id = $.trim(_id.toUpperCase());
var idArray = this._splitId(id);
if (idArray.length <= 0) {
returnObj.status = false;
returnObj.info = "身份证号码格式错误";
return returnObj;
}
if (id.length != 18) {
returnObj.status = false;
returnObj.info = " 身份证号码必须是18位";
return returnObj;
}
var checksum = id.substring(17, 18);
var sum = 0;
for ( var i = 1; i <= idArray.length; i++) {
var Ai = idArray[i - 1];
var Wi = this._getWeightingFactor(i);
if (Wi != -1) {
sum += Ai * Wi;
}
}
var mod = sum % 11;
if (this._getChecksum(mod) == checksum) {
returnObj.status = true;
return returnObj;
} else {
returnObj.status = false;
returnObj.info = " 身份证号码输入错误";
return returnObj;
}
},
_splitId : function(_id) {
var len = _id.length;
var array = new Array();
for ( var i = 0; i < len - 1; i++) {
array.push(_id.charAt(i));
}
return array;
},
_getWeightingFactor : function(_index) {
switch (_index) {
case 1:return 7;
case 2:return 9;
case 3:return 10;
case 4:return 5;
case 5:return 8;
case 6:return 4;
case 7:return 2;
case 8:return 1;
case 9:return 6;
case 10:return 3;
case 11:return 7;
case 12:return 9;
case 13:return 10;
case 14:return 5;
case 15:return 8;
case 16:return 4;
case 17:return 2;
default:return -1;
}
},
_getChecksum : function(_mod) {
switch (_mod) {
case 0:return 1;
case 1:return 0;
case 2:return "X";
case 3:return 9;
case 4:return 8;
case 5:return 7;
case 6:return 6;
case 7:return 5;
case 8:return 4;
case 9:return 3;
case 10:return 2;
default:return -1;
}
}
};
// PHP版
<?php
/**
*大陆居民身份证检验
**/
class IdCardValid{
static private $info; // 返回信息
static private $status;// 返回状态
static private $mark;// 返回类型标志
/**
*判断身份证号
*@parem 18位的居民身份证号
*@parem返回数据类型 false:json true:array
*@return 返回JSON数组类型的提示数据
**/
static function isIdCard($_id, $mark=false){
self::$mark = $mark ;
$id = trim( strtoupper($_id) );
if( strlen($id) <= 0){
self::$status = false;
self::$info = " 身份证号码格式错误";
return self::_notice();
}
if( strlen($id) != 18){
self::$status = false;
self::$info = " 身份证号码必须是18位";
return self::_notice();
}
$sum = 0 ;
$weightFactor = array(0,7,9,10,5,8,4,2,1,6,3,7,9,10,5,8,4,2,-1);
for($i = 1; $i <= strlen($id); $i++) {
$Ai = $id{$i - 1};
$Wi = $weightFactor[$i];
if ($Wi != -1) {
$sum += $Ai * $Wi;
}
}
$checkSum = array(1,0,'X',9,8,7,6,5,4,3,2,-1);
$mod = $checkSum[ $sum % 11 ] ;
if( $mod == $id{17} ){
self::$status = true;
self::$info = 'OK';
return self::_notice();
}else{
self::$status = false;
self::$info = " 身份证号码输入错误";
return self::_notice();
}
}
/**
*返回信息 0 Array 1 JSON数据
**/
static private function _notice(){
$return['status'] = self::$status ;
$return['info'] = self::$info ;
if( self::$mark ){
return json_encode($return);
}else{
return $return ;
}
}
}
// 测试用例
print_r(IdCardValid::isIdCard('510623198810089039')); // 错误
print_r(IdCardValid::isIdCard('51062319881008903X')); // 正确
print_r(IdCardValid::isIdCard('51062319881')); // 格式不对
print_r(IdCardValid::isIdCard('')); // 不能为空
?>