laravel 表单验证 api自定义错误信息返回json 与 路由别名场景验证
admin 36 2019-12-01 16:04:46
<?php
namespace App\Http\Requests;
use Illuminate\Foundation\Http\FormRequest;
use Illuminate\Contracts\Validation\Validator;
use Illuminate\Http\Exceptions\HttpResponseException;
class ApiRequest extends FormRequest
{
protected $rules=[]; //规则
protected $scene=[]; //场景
protected $attribute=[]; //属性说明
protected $messages=[ //错误信息
"required" => ":attribute 不能为空",
"between" => ":attribute 长度必须在 :min 和 :max 之间",
"email" => ":attribute 格式错误",
"regex" => ":attribute 格式错误",
"mobile" => ":attribute 格式错误",
'date_format' => ':attribute 与给定的格式 :format 不符合',
'unique' => ':attribute 已存在',
'max' => [
'numeric' => ':attribute 的最大长度为 :max 位',
'file' => ':attribute 的最大为 :max',
'string' => ':attribute 的最大长度为 :max 字符',
'array' => ':attribute 的最大个数为 :max 个.',
],
'in' => ':attribute 不在操作范围!',
"numeric" => ":attribute 不为数字",
"integer" => ":attribute 不为整数",
];
/**
* 自定义错误信息 返回json
*
* @param Validator $validator
*/
public function failedValidation(Validator $validator)
{
throw (new HttpResponseException(response()->json([
'status' => false,
'code' => '500',
'message' => $validator->errors()->first(),
'data' => [],
],200)));
}
/**
* 路由别名场景验证 (根据路由别名不同规则验证)
*/
public function sceneValidator(){
if(!empty($this->scene)){
$routeName = $this->route()->getName(); //获取路由别名
if($routeName && array_key_exists($routeName,$this->scene)){
$sceneRules = $this->scene[$routeName];
$rules=[];
foreach ($sceneRules as $key=>$value){
if(is_numeric($key)){
$rules[$value] = $this->rules[$value];
}else{
$rules[$key] = $value;
}
}
$this->rules = $rules;
}
}
}
/**
* Determine if the user is authorized to make this request.
*
* @return bool
*/
public function authorize()
{
return true;
}
/**
* Get the validation rules that apply to the request.
*
* @return array
*/
public function rules()
{
$this->sceneValidator();
return $this->rules;
}
/**
* 自定义属性说明
* @return array
*/
public function attributes()
{
return $this->attribute;
}
/**
* 自定义错误消息
* @return array
*/
public function messages()
{
return $this->messages;
}
}
To share this paste please copy this url and send to your friends
预览
还没有评论.
最新分享
- PHP用redis实现计数器功能从而实现限流
PHP | 48 | 2周前
- PHP批量下载QQ空间相册照片链接
PHP | 42 | 2周前
- PHP对一个接口进行请求次数限制
PHP | 32 | 2周前
- PHP汉字转拼音类文件
PHP | 34 | 2周前
- laravel 表单验证 api自定义错误信息返回json 与 路由别名场景验证
PHP | 36 | 2周前
- QQ或微信内打开网站提示用浏览器打开代码
PHP | 55 | 3周前
- 简易防CC攻击刷新跳转代码
PHP | 53 | 3周前