面对更复杂的情况,您可以创建一个「表单请求」来应对更复杂的验证逻辑。表单请求是一个包含了验证逻辑的自定义请求类。要创建一个表单请求类,请使用 make:request
php artisan make:request CheckUser
验证代码
<?php namespace App\Http\Requests\Admin; use Illuminate\Foundation\Http\FormRequest; use Illuminate\Contracts\Validation\Validator; use Illuminate\Http\Exceptions\HttpResponseException; use Illuminate\Support\Facades\Route; class CheckUser 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() { return [ 'name' => 'required', 'password' => 'required', 'email' => 'required', 'realname' => 'required', 'tel' => 'required', ]; } /** * 获取已定义验证规则的错误消息。 * * @return array */ public function messages() { return [ 'name.required' => '账号不能为空', 'password.required' => '密码不能为空', 'email.required' => '邮箱不能为空', 'realname.required' => '姓名不能为空', 'tel.required' => '电话不能为空', ]; } // ajax返回 public function failedValidation(Validator $validator) { throw (new HttpResponseException(response()->json([ 'code' => 1, 'msg' => $validator->errors()->first(), ], 0))); } } ?>
控制器调用验证
<?php public function add(CheckUser $request){ } ?>
这样,用户在提交数据,laravel后端就会自动对提交过来的数据进行校验。
文章评论(0)