验证器代码:
protected $rule = [
'idcard|身份证' => 'require|checkIdCard',
];
protected $message = [
'idcard.require' => '身份证必须填写',
'idcard.checkIdCard' => '身份证格式有误',
];
protected $scene = [
'edit' => [
'idcard'
],
];
//验证身份证
public function checkIdCard($idcard) {
if(empty($idcard)){
return false;
}else{
$idcard = strtoupper($idcard); # 如果是小写x,转化为大写X
if(strlen($idcard) != 18 && strlen($idcard) != 15){
return false;
}
# 如果是15位身份证,则转化为18位
if(strlen($idcard) == 15){
# 如果身份证顺序码是996 997 998 999,这些是为百岁以上老人的特殊编码
if (array_search(substr($idcard, 12, 3), array('996', '997', '998', '999')) !== false) {
$idcard = substr($idcard, 0, 6) . '18' . substr($idcard, 6, 9);
} else {
$idcard = substr($idcard, 0, 6) . '19' . substr($idcard, 6, 9);
}
# 加权因子
$factor = array(7, 9, 10, 5, 8, 4, 2, 1, 6, 3, 7, 9, 10, 5, 8, 4, 2);
# 校验码对应值
$code = array('1', '0', 'X', '9', '8', '7', '6', '5', '4', '3', '2');
$checksum = 0;
for ($i = 0; $i < strlen($idcard); $i++) {
$checksum += substr($idcard, $i, 1) * $factor[$i];
}
$idcard = $idcard . $code[$checksum % 11];
}
# 验证身份证开始
$IDCardBody = substr($idcard, 0, 17); # 身份证主体
$IDCardCode = strtoupper(substr($idcard, 17, 1)); # 身份证最后一位的验证码
# 加权因子
$factor = array(7, 9, 10, 5, 8, 4, 2, 1, 6, 3, 7, 9, 10, 5, 8, 4, 2);
# 校验码对应值
$code = array('1', '0', 'X', '9', '8', '7', '6', '5', '4', '3', '2');
$checksum = 0;
for ($i = 0; $i < strlen($IDCardBody); $i++) {
$checksum += substr($IDCardBody, $i, 1) * $factor[$i];
}
$validateIdcard = $code[$checksum % 11]; # 判断身份证是否合理
if($validateIdcard != $IDCardCode){
return false;
}else{
return true;
}
}
}
调用验证:
$post_data = input('post.');
$validate = new UserValidate();
if(!$validate->scene('edit')->check($post_data)){
$this->error($validate->getError());
}
返回结果:
{"code":0,"msg":"身份证格式有误","time":"1689091502","data":null}