使用Laravel的表单验证器

1、使用默认的验证信息

  1. $rules = [
  2. 'phone' => 'required'
  3. ];
  4. $validator = Validator::make($request->all(), $rules);
  5. if ($validator->fails()) {
  6. $message = $validator->errors()->first();
  7. return new JsonResponse(['code' => '10501', 'msg' => $message, 'data' => []]);
  8. }

2、使用自定义的验证信息

  1. $rules = [
  2. 'phone' => 'required'
  3. ];
  4. $messages = [
  5. 'phone.required' => 'phone 是必填字段'
  6. ];
  7. $validator = Validator::make($request->all(), $rules, $messages);
  8. if ($validator->fails()) {
  9. $message = $validator->errors()->first();
  10. return new JsonResponse(['code' => '10501', 'msg' => $message, 'data' => []]);
  11. }

3、创建表单请求进行验证

  • 创建表单请求文件:php artisan make:request ExampleRequest
  • 表单请求文件内容:
  1. <?php
  2. namespace App\Http\Requests;
  3. use Illuminate\Contracts\Validation\Validator;
  4. use Illuminate\Foundation\Http\FormRequest;
  5. use Illuminate\Http\Exceptions\HttpResponseException;
  6. use Illuminate\Http\JsonResponse;
  7. class ExampleRequest extends FormRequest
  8. {
  9. /**
  10. * Determine if the user is authorized to make this request.
  11. *
  12. * @return bool
  13. */
  14. public function authorize()
  15. {
  16. return true;
  17. }
  18. /**
  19. * Get the validation rules that apply to the request.
  20. *
  21. * @return array
  22. */
  23. public function rules()
  24. {
  25. return [
  26. 'title' => 'required|max:20',
  27. 'name' => ['required', new Uppercase()],
  28. ];
  29. }
  30. /**
  31. * 获取已定义的验证规则的错误消息。
  32. *
  33. * @return array
  34. */
  35. public function messages()
  36. {
  37. return [
  38. 'title.required' => 'A title is required',
  39. 'title.max' => 'The title may not be greater than 20 characters.',
  40. ];
  41. }
  42. /**
  43. * 验证失败,返回错误信息
  44. *
  45. * @param Validator $validator
  46. * @throws
  47. */
  48. protected function failedValidation(Validator $validator)
  49. {
  50. if ($this->wantsJson() || $this->ajax()) {
  51. throw new HttpResponseException(
  52. new JsonResponse([
  53. 'code' => 500,
  54. 'msg' => $validator->errors()->first(),
  55. 'data' => new \stdClass()
  56. ])
  57. );
  58. } else {
  59. parent::failedValidation($validator);
  60. }
  61. }
  62. }
  • 在控制器中使用 ExampleRequest
  1. <?php
  2. namespace App\Http\Controllers;
  3. use App\Http\Controllers\Controller;
  4. use App\Http\Requests\ExampleRequest;
  5. class ExampleController extends Controller
  6. {
  7. public function valid(ExampleRequest $request)
  8. {
  9. $params = $request->all();
  10. dd($params);
  11. }
  12. }


评论 0

发表评论

Top