使用Laravel的表单验证器

本文介绍了如何在Laravel中进行表单验证,包括使用默认验证信息、自定义验证信息以及通过创建表单请求类来执行验证。详细阐述了表单请求文件的创建及其在控制器中的应用。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

1、使用默认的验证信息

$rules = [
    'phone' => 'required'
];
$validator = Validator::make($request->all(), $rules);
if ($validator->fails()) {
    $message = $validator->errors()->first();
    return new JsonResponse(['code' => '10501', 'msg' => $message, 'data' => []]);
}

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

$rules = [
    'phone' => 'required'
];
$messages = [
    'phone.required' => 'phone 是必填字段'
];
$validator = Validator::make($request->all(), $rules, $messages);
if ($validator->fails()) {
    $message = $validator->errors()->first();
    return new JsonResponse(['code' => '10501', 'msg' => $message, 'data' => []]);
}

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

  • 创建表单请求文件:php artisan make:request ExampleRequest
  • 表单请求文件内容:
<?php

namespace App\Http\Requests;

use Illuminate\Contracts\Validation\Validator;
use Illuminate\Foundation\Http\FormRequest;
use Illuminate\Http\Exceptions\HttpResponseException;
use Illuminate\Http\JsonResponse;

class ExampleRequest 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 [
            'title' => 'required|max:20',
            'name'  => ['required', new Uppercase()],
        ];
    }

    /**
     * 获取已定义的验证规则的错误消息。
     *
     * @return array
     */
    public function messages()
    {
        return [
            'title.required' => 'A title is required',
            'title.max'  => 'The title may not be greater than 20 characters.',
        ];
    }

    /**
     * 验证失败,返回错误信息
     *
     * @param Validator $validator
     * @throws
     */
    protected function failedValidation(Validator $validator)
    {
        if ($this->wantsJson() || $this->ajax()) {
            throw new HttpResponseException(
                new JsonResponse([
                    'code' => 500,
                    'msg' => $validator->errors()->first(),
                    'data' => new \\stdClass()
                ])
            );
        } else {
            parent::failedValidation($validator);
        }
    }
}
  • 在控制器中使用 ExampleRequest
<?php

namespace App\Http\Controllers;

use App\Http\Controllers\Controller;
use App\Http\Requests\ExampleRequest;

class ExampleController extends Controller
{
    public function valid(ExampleRequest $request)
    {
        $params = $request->all();
        dd($params);
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值