标签:else 控制器 live strong validator reg strlen boot match
首先在 Providers\AppServiceProvider.php 文件中自定义 手机号和身份证号验证
1 // AppServiceProvider.php 文件 2 3 <?php 4 namespace App\Providers; 5 6 use Illuminate\Support\ServiceProvider; 7 use Illuminate\Support\Facades\Validator; 8 use Illuminate\Support\Facades\DB; 9 10 class AppServiceProvider extends ServiceProvider 11 { 12 /** 13 * Bootstrap any application services. 14 * 15 * @return void 16 */ 17 public function boot() 18 { 19 //验证手机号 20 \Validator::extend(‘phone‘, function ($attribute, $value, $parameters, $validator) { 21 $pattern = ‘/^1[3456789]{1}\d{9}$/‘; 22 $res = preg_match($pattern, $value); 23 24 return $res > 0; 25 }); 26 \Validator::replacer(‘phone‘, function ($message, $attribute, $rule, $parameters) { 27 return $message; 28 //return str_replace($attribute,$rule,$message); 29 }); 30 31 //验证身份证号 32 \Validator::extend(‘identityCard‘, function ($attribute, $value, $parameters, $validator) { 33 return $this->checkIdentityCard($value); 34 }); 35 \Validator::replacer(‘identityCard‘, function ($message, $attribute, $rule, $parameters) { 36 return $message; 37 //return str_replace($attribute,$rule,$message); 38 }); 39 } 40 41 /** 42 * 验证身份证 43 * @param $idCard 44 * @return bool 45 * @author centphp.com 46 * @date 2020/5/1 47 */ 48 public static function checkIdentityCard($idCard) 49 { 50 // 只能是18位 51 if (strlen($idCard) != 18) { 52 return false; 53 } 54 // 取出本体码 55 $idcard_base = substr($idCard, 0, 17); 56 // 取出校验码 57 $verify_code = substr($idCard, 17, 1); 58 // 加权因子 59 $factor = array(7, 9, 10, 5, 8, 4, 2, 1, 6, 3, 7, 9, 10, 5, 8, 4, 2); 60 // 校验码对应值 61 $verify_code_list = array(‘1‘, ‘0‘, ‘X‘, ‘9‘, ‘8‘, ‘7‘, ‘6‘, ‘5‘, ‘4‘, ‘3‘, ‘2‘); 62 // 根据前17位计算校验码 63 $total = 0; 64 for ($i = 0; $i < 17; $i++) { 65 $total += substr($idcard_base, $i, 1) * $factor[$i]; 66 } 67 // 取模 68 $mod = $total % 11; 69 // 比较校验码 70 if ($verify_code == $verify_code_list[$mod]) { 71 return true; 72 } else { 73 return false; 74 } 75 } 76 } 77 ?>
在控制器中使用如下:
1 <?php 2 namespace App\Modules\Live\Http\Controllers; 3 4 use Illuminate\Http\Request; 5 class IndexController extends Controller 6 { 7 public function store(Request $request) 8 { 9 $messages = [ 10 ‘idcard.required‘=>‘身份证号不能为空‘, 11 ‘idcard.identity_card‘=>‘身份证号不合法‘, 12 ‘email.required‘=>‘邮箱不能为空‘, 13 ‘email.email‘=>‘邮箱不合法‘, 14 ‘tel.required‘ => ‘手机号不能为空‘, 15 ‘tel.phone‘ => ‘手机号不合法‘, 16 ]; 17 $rules = [ 18 ‘idcard‘ => ‘required|identityCard‘, 19 ‘email‘ => ‘required|email‘, 20 ‘tel‘ => ‘required|phone‘, 21 ]; 22 $this->validate($request, $rules,$messages); 23 } 24 } 25 ?>
标签:else 控制器 live strong validator reg strlen boot match
原文地址:https://www.cnblogs.com/Jessie-candy/p/13188812.html