Commit 0f8aa89e by 赵增煜

增加身份证校验方法

parent 49e212fc
...@@ -68,7 +68,7 @@ public function add(Request $request) ...@@ -68,7 +68,7 @@ public function add(Request $request)
$idValidator = new IdValidator(); $idValidator = new IdValidator();
// if (! $idValidator->isValid($data['id_card'])) { // if (! $idValidator->isValid($data['id_card'])) {
// if( !in_array(strlen($data['id_card']),[15,18])){ // if( !in_array(strlen($data['id_card']),[15,18])){
if (isset($data['id_card']) && strlen($data['id_card']) != 18) { // 身份证非必填项 if (isset($data['id_card']) && !validateIDCard($data['id_card'])) { // 身份证非必填项
return $this->failed('身份证格式错误'); return $this->failed('身份证格式错误');
} }
...@@ -116,7 +116,7 @@ public function update(Request $request) ...@@ -116,7 +116,7 @@ public function update(Request $request)
// 验证身份证格式 // 验证身份证格式
$idValidator = new IdValidator(); $idValidator = new IdValidator();
// if (! $idValidator->isValid($id_card)) { // if (! $idValidator->isValid($id_card)) {
if (isset($id_card) && strlen($id_card) != 18) { if (isset($id_card) && !validateIDCard($id_card)) {
return $this->failed('身份证格式错误'); return $this->failed('身份证格式错误');
} }
......
...@@ -177,3 +177,58 @@ function validateBirthday($birthday) ...@@ -177,3 +177,58 @@ function validateBirthday($birthday)
} }
} }
if (! function_exists('validateIDCard')) {
function validateIDCard($idCard) {
// 长度检查
if (!preg_match('/^\d{15}$|^\d{17}[\dXx]$/', $idCard)) {
return false;
}
// 15位转18位(如果是15位身份证)
if (strlen($idCard) === 15) {
$idCard = convertIDCard15to18($idCard);
}
// 检查出生日期
$birthDate = substr($idCard, 6, 8); // 提取出生日期部分
$year = substr($birthDate, 0, 4);
$month = substr($birthDate, 4, 2);
$day = substr($birthDate, 6, 2);
if (!checkdate((int)$month, (int)$day, (int)$year)) {
return false;
}
// 校验码验证
return checkIDCardChecksum($idCard);
}
function convertIDCard15to18($idCard15) {
// 15位身份证转换为18位
$prefix = substr($idCard15, 0, 6) . '19' . substr($idCard15, 6);
$checksum = calculateChecksum($prefix);
return $prefix . $checksum;
}
function checkIDCardChecksum($idCard18) {
// 检查身份证校验码
$base = substr($idCard18, 0, 17);
$checksum = calculateChecksum($base);
return strtoupper($checksum) === strtoupper($idCard18[17]);
}
function calculateChecksum($base) {
// 计算校验码
$weights = [7, 9, 10, 5, 8, 4, 2, 1, 6, 3, 7, 9, 10, 5, 8, 4, 2];
$checksumMap = ['1', '0', 'X', '9', '8', '7', '6', '5', '4', '3', '2'];
$sum = 0;
for ($i = 0; $i < 17; $i++) {
$sum += $base[$i] * $weights[$i];
}
return $checksumMap[$sum % 11];
}
}
\ No newline at end of file
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or sign in to comment