You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

68 lines
1.6 KiB

This file contains ambiguous Unicode characters!

This file contains ambiguous Unicode characters that may be confused with others in your current locale. If your use case is intentional and legitimate, you can safely ignore this warning. Use the Escape button to highlight these characters.

<?php
namespace App\Rules;
use Illuminate\Contracts\Validation\Rule;
class Idcard implements Rule
{
/**
* Create a new rule instance.
*
* @return void
*/
public function __construct()
{
//
}
/**
* Determine if the validation rule passes.
*
* @param string $attribute
* @param mixed $value
* @return bool
*/
public function passes($attribute, $value)
{
if (strlen($value) != 18) {
return false;
}
# 转化为大写如出现x
$idcard = strtoupper($value);
# 加权因子
$wi = array(7, 9, 10, 5, 8, 4, 2, 1, 6, 3, 7, 9, 10, 5, 8, 4, 2);
$ai = array('1', '0', 'X', '9', '8', '7', '6', '5', '4', '3', '2');
# 按顺序循环处理前17位
$sigma = 0;
# 提取前17位的其中一位并将变量类型转为实数
for ($i = 0; $i < 17; $i++) {
$b = (int)$idcard[$i];
# 提取相应的加权因子
$w = $wi[$i];
# 把从身份证号码中提取的一位数字和加权因子相乘,并累加
$sigma += $b * $w;
}
# 计算序号
$sidcard = $sigma % 11;
# 按照序号从校验码串中提取相应的字符。
$check_idcard = $ai[$sidcard];
if ($idcard[17] == $check_idcard) {
return true;
} else {
return false;
}
}
/**
* Get the validation error message.
*
* @return string
*/
public function message()
{
return '身份证号码格式错误';
}
}