首先在 Providers\AppServiceProvider.php 文件中自定义 手机号和身份证号验证

 // AppServiceProvider.php 文件

 <?php
namespace App\Providers; use Illuminate\Support\ServiceProvider;
use Illuminate\Support\Facades\Validator;
use Illuminate\Support\Facades\DB; class AppServiceProvider extends ServiceProvider
{
/**
* Bootstrap any application services.
*
* @return void
*/
public function boot()
{
//验证手机号
\Validator::extend('phone', function ($attribute, $value, $parameters, $validator) {
$pattern = '/^1[3456789]{1}\d{9}$/';
$res = preg_match($pattern, $value); return $res > 0;
});
\Validator::replacer('phone', function ($message, $attribute, $rule, $parameters) {
return $message;
//return str_replace($attribute,$rule,$message);
}); //验证身份证号
\Validator::extend('identityCard', function ($attribute, $value, $parameters, $validator) {
return $this->checkIdentityCard($value);
});
\Validator::replacer('identityCard', function ($message, $attribute, $rule, $parameters) {
return $message;
//return str_replace($attribute,$rule,$message);
});
} /**
* 验证身份证
* @param $idCard
* @return bool
* @author centphp.com
* @date 2020/5/1
*/
public static function checkIdentityCard($idCard)
{
// 只能是18位
if (strlen($idCard) != 18) {
return false;
}
// 取出本体码
$idcard_base = substr($idCard, 0, 17);
// 取出校验码
$verify_code = substr($idCard, 17, 1);
// 加权因子
$factor = array(7, 9, 10, 5, 8, 4, 2, 1, 6, 3, 7, 9, 10, 5, 8, 4, 2);
// 校验码对应值
$verify_code_list = array('1', '0', 'X', '9', '8', '7', '6', '5', '4', '3', '2');
// 根据前17位计算校验码
$total = 0;
for ($i = 0; $i < 17; $i++) {
$total += substr($idcard_base, $i, 1) * $factor[$i];
}
// 取模
$mod = $total % 11;
// 比较校验码
if ($verify_code == $verify_code_list[$mod]) {
return true;
} else {
return false;
}
}
}
?>

在控制器中使用如下:

 <?php
namespace App\Modules\Live\Http\Controllers; use Illuminate\Http\Request;
class IndexController extends Controller
{
public function store(Request $request)
{
$messages = [
'idcard.required'=>'身份证号不能为空',
'idcard.identity_card'=>'身份证号不合法',
'email.required'=>'邮箱不能为空',
'email.email'=>'邮箱不合法',
'tel.required' => '手机号不能为空',
'tel.phone' => '手机号不合法',
];
$rules = [
'idcard' => 'required|identityCard',
'email' => 'required|email',
'tel' => 'required|phone',
];
$this->validate($request, $rules,$messages);
}
}
?>
05-06 04:26