Laravel创建表单请求验证可以使用 make:request 来创建,具体创建方式可以参考这篇文章:laravel5.8使用ajax+验证器验证实现ajax返回验证数据
我们创建一个在CheckAdmin.php验证文件
编写如下代码:
<?php namespace App\Http\Requests\Admin; use Illuminate\Foundation\Http\FormRequest; use Illuminate\Contracts\Validation\Validator; use Illuminate\Http\Exceptions\HttpResponseException; class CheckAdmin extends FormRequest { /** * 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() { if (Route::currentRouteName() == 'admin.admin.edit') { return [ 'admin_name' => 'sometimes|required', 'admin_realname' => 'sometimes|required', 'stop' => 'sometimes|required', ]; }else{ return [ 'admin_name' => 'sometimes|required', 'admin_realname' => 'sometimes|required', 'admin_password' => 'sometimes|required|confirmed|min:6', 'password_confirmation ' => 'sometimes|required', 'stop ' => 'sometimes|required', ]; } } /** * 获取已定义验证规则的错误消息。 * * @return array */ public function messages() { return [ 'admin_name.required' => '请输入账号', 'admin_realname.required' => '请输入姓名', 'admin_password.required' => '请输入密码', 'admin_password.min' => '密码长度不能小于6个字符', 'password_confirmation.required' => '请输入确认密码', 'admin_password.confirmed'=>"密码与确认密码不一致", 'stop.required' => '请选择账号状态', ]; } // ajax返回 public function failedValidation(Validator $validator) { throw (new HttpResponseException(response()->json([ 'code' => 500, 'msg' => $validator->errors()->first(), ], 200))); } } ?>
解析:这部分代码主要是以下这段,我们通过获取路由别名来判断执行那段验证规则:
<?php if (Route::currentRouteName() == 'admin.admin.edit') { return [ 'admin_name' => 'sometimes|required', 'admin_realname' => 'sometimes|required', 'stop' => 'sometimes|required', ]; }else{ return [ 'admin_name' => 'sometimes|required', 'admin_realname' => 'sometimes|required', 'admin_password' => 'sometimes|required|confirmed|min:6', 'password_confirmation ' => 'sometimes|required', 'stop ' => 'sometimes|required', ]; } ?>
我们实现的是一个添加用户场景和修改用户信息场景。这样通过上面的判断就可以对其分别验证。
文章评论(0)