一、参数验证,拒绝if...else对参数的校验
1、根据接口返回规则
{
"code": 1062,
"message": "参数错误"
}
方法一:model方法验证
新建基础控制器HttpBaseController
all(), $rule, $message);
if($validator->fails()){
foreach($validator->errors()->getMessages() as $message){
$sys_err = config('sys_error.sys_error');
if(is_array($message[0])){
return json_encode($response);
}
$this->code = $message[0];
if (!isset($sys_err[$this->code])) {
$response = [
'code' => 1062,
'message' => $message[0] ?? '参数错误',
];
return json_encode($response);
}
return re_err($message[0]);
}
}
return null;
}catch (\Exception $e){
throw_err(501);
}
}
}
2、类的使用,控制器继承这个基础类
如 DistributeBaseController
类的继承 class DistributeBaseController extends HttpBaseController
3、验证方法使用
使用验证规则放在Model中的方法里
'required|regex:/^[a-zA-Z][a-zA-Z0-9]{5,11}$/',
'email' => 'required|email',
'password' => 'required|min:6',
'old_password' => 'required|min:6',
'mobile_no' => 'required|numeric|digits:11',
];
foreach ($array as $item) {
$data[$item] = $rules[$item];
}
return $data;
}
public function message()
{
return [
'username.required' => '1062',
'username.unique' => '用户名已存在',
'username.regex' => '用户名不合法',
'email.required' => '请填写邮箱地址',
'email.unique' => '邮箱名已存在',
'email.email' => '邮箱名不合法',
'password.required' => ['code'=>'1062','message'=>'请填写密码'],
'password.min' => '密码至少需要 :min 位字符',
'mobile_no.required' => '请填写手机号',
'mobile_no.unique' => '手机号已存在',
'mobile_no.numeric' => '手机号必须为数字',
'mobile_no.digits' => '手机号必须为 :digits 位',
];
}
}
调用
$user = new TestModel();
$validator_user = $this->ruleValidator(
$this->request,
$user->rules(['username', 'password']),
$user->message());
if ($validator_user) {
return $validator_user;
}
方法二:临时验证
1、重写验证抛错方法throwValidationException
code = $validator->errors()->first();
if (!isset($sys_err[$this->code])) {
$response = [
'code' => 1062,
'message' => $this->code ?? '参数错误',
];
throw new ValidationException($validator, $response);
}
if ($this->message == '') {
$message = $sys_err[$this->code];
}
$response = [
'code' => $validator->errors()->first(),
'message' => $message,
];
throw new ValidationException($validator, $response);
}
}
2、类的使用,控制器继承这个基础类
如 DistributeBaseController
类的继承 class DistributeBaseController extends HttpBaseController
3、控制器使用
$this->validate($this->request, [
'title' => 'required|max:255',
'mobile' => 'required|numeric|digits:11'
], [
'title.required' => '标题错误',
'mobile.required' => '请填写手机号',
'mobile.unique' => '手机号已存在',
'mobile.digits' => '手机号必须为 :digits 位',
]);