RestPasswdValidator
<?php namespace App\Service; use Illuminate\Support\Facades\Validator; use App\Service\BaseValidator; class RestPasswdValidator extends BaseValidator{ public $validatorsMessage; public $rules; public $message; protected $data; public $validator; public function __construct() { call_user_func_array([$this,'validator_rules'],[]); } public function validator_rules(){ //验证规则 $this->rules = [ 'mobile' => 'required', 'password' => 'required|min:6|max:16', 'code' => 'required', ]; $this->message = LangConfig('AuthMobileLoginValidator'); } /** * 处理返回的data字段 * @return mixed */ public function setFields(){ array_walk_recursive($this->data,function(&$val,$key){ $val = trim($val); }); } /** * 验证码器钩子 */ public function hookAfter(){ if (!preg_match_all("/^1[3456789]\d{9}$/", trim(request()->input('mobile')))) { $this->hookList = ['filed'=>'mobile','message'=>LangConfig('MobileFormatError')]; } } }
'AuthMobileLoginValidator'=>[ 'mobile.required' => '手机号必填', 'password.required' => '密码必填', 'password.min' => '密码最少6位', 'password.max' => '密码最多16位', 'code.required'=>'短信验证码必填', ],
BaseValidator
<?php namespace App\Service; use Illuminate\Support\Facades\Validator; abstract class BaseValidator { public $validatorsMessage; public $rules; public $message; protected $data; public $validator; public $hookList = []; /* * 实现validator_rules * rule规则 */ abstract public function validator_rules(); /** * 处理返回的data字段 * @return mixed */ abstract public function setFields(); /** * @param $requestData * 验证数据合法性 */ public function make($requestData){ $this->data = $requestData; $this->validator = Validator::make($requestData, $this->rules,$this->message); $this->hook(); } public function hook(){ call_user_func_array([$this,'hookAfter'],[]); $this->validator->after(function($validator){ if(!empty($this->hookList)){ $validator->errors()->add($this->hookList['filed'],$this->hookList['message']); } }); } /** * 获取验证消息 * @return bool|mixed */ public function getMessage(){ if($this->validator->fails() > 0){ $messages = $this->validator->errors(); return [0,$messages->first()]; }else{ return [1,'ok']; } } /* *返回处理过后的数据 */ public function getData(){ call_user_func_array([$this,'setFields'],[]); return $this->data; } }
控制器中使用
//验证数据合法性 $rule = new RestPasswdValidator(); $rule->make($request->only("mobile","password","code")); list($err_code,$err_smg) = $rule->getMessage(); if(!$err_code){ throw new UserApiException($err_smg,501); } $data = $rule->getData();
本文来自博客园,作者:孙龙-程序员,转载请注明原文链接:https://www.cnblogs.com/sunlong88/articles/11102694.html