Laravel学习之验证器

/ 0评 / 0

laravel提供了强大的验证功能模块,可以快速的验证传入内容或HTTP请求,除了基础的格式验证之外还支持通过数据库验证。

使用方法

为了内容的统一,这块内容里我们只讨论使用方法,验证规则将放在文末。

基础使用方法

可以直接使用request中的validate方法,传入验证规则创建,如果检查到错误将直接抛出。

validate接受一个数组,键值为验证内容的键值,内容是各项规则,用 | 分割

public function store(Request $request)
{
    $validated = $request->validate([
        'title' => 'required|unique:posts|max:255',
        'body' => 'required',
    ]);

    // 博客文章验证通过...
}

错误信息处理

全局更改错误抛出语言

这里的错误信息可以通过更改 lang/en/validation.php 文件修改,需要汉化版本可以:

  1. 把 resources\lang 下en 的文件夹 复制在同一目录并改名为 zn
  2. zn 中的 validation.php文件修改为 https://laravel-china.org/articles/5840/validation-validation-in-laravel-returns-chinese-prompt(如不能下载,文末有原文件代码可供拷贝)
  3. 修改config 目录下的app.php 文件 'locale' => 'zn',

通过继承request类实现脱离控制器验证

如果要在每一个控制器中一个个去写验证器,不仅冗余也不优雅,我们可以将验证器放到request类中。

// 终端中执行
php artisan make:request StorePostRequest

使用rules方法定义规则

public function rules()
{
    return [
        'title' => 'required|unique:posts|max:255',
        'body' => 'required',
    ];
}

使用message方法定义错误信息

public function messages()
{
    return [
        'title.required' => 'A title is required',
        'body.required' => 'A message is required',
    ];
}

使用attributes方法对抛出错误的属性内容更改

默认情况下如require抛出错误 :attribute 字段是必须的, 若你使用了中文语言包对应内容为 title是必须的。

通过attribute我们可以对属性值更改。

public function attributes()
{
    return [
        'email' => '电子邮箱',
    ];
}

更进一步封装

通过更进一步的封装,我们可以将不同的方法定义转为参数定义,看起来更加简洁,也能基本解决一个Request类只能使用在一个方法的情况。

通过封装BaseRequest,我们将路由中类方法名称对应到具体的规则中,实现一个验证类对应多个方法。

创建基础类

<?php


namespace App\Http\Request;

use App\Http\Exception\HttpException;
use Illuminate\Foundation\Http\FormRequest;
use Illuminate\Contracts\Validation\Validator;

class BaseRequest extends FormRequest
{

    /**
     * 定义验证规则
     *
     * @return array
     */
    public function rules()
    {
        $rule_action = $this->route()->getActionMethod();
        if ($this->$rule_action)
            return $this->$rule_action['rules'] ?? $this->getDefaultRules();
        return $this->getDefaultRules();
    }


    /**
     * 默认 验证规则
     * @return array
     */
    protected function getDefaultRules()
    {
        return [];
    }

    /**
     * 验证消息通过json抛出(api开发时用到)
     * @param Validator $validator
     */
    protected function failedValidation(Validator $validator)
    {
        throw new HttpException(response()->json([
            'status' => 500,
            'message' => $validator->errors()->first()
        ]));
    }

    /**
     * 统一定义验证规则的自定义错误消息。
     * @return array
     */
    public function messages()
    {
        $rule_action = $this->route()->getActionMethod();
        if ($this->$rule_action)
            return $this->$rule_action['message'] ?? [];
        return [];
    }

    /**
     * 统一定义验证规则的自定义属性。
     * @return array
     */
    public function attributes()
    {
        $rule_action = $this->route()->getActionMethod();
        if ($this->$rule_action)
            return $this->$rule_action['attributes'] ?? [];
        return [];
    }
}

创建验证reuqest

<?php
namespace App\Http\Request;

class DispatchRequest extends BaseRequest
{
    public $add = [
        'rules' => [
            'name' => 'required|bail',
            'userIds' => 'required|array|min:1|bail|exists:users,id'
        ],
        'message' => [
            'name.required' => '请输入被派遣单位名称',
            'userIds.required' => '请选择被派遣单位可见范围',
            'userIds.min' => '请选择被派遣单位可见范围',
            'userIds.exists' => '选择的员工不存在'
        ]
    ];
}

高级规则

基础规则可以直接在文末中查看验证规则的汉化文件,将规则与错误信息一一对应

bail

在首次验证失败后立即终止验证

exists 数据库验证字段是否存在

验证字段内容在数据库列中是否存在,不存在则返回错误。

'state' => 'exists:表名,列名'
'state' => 'exists:states,abbreviation'
'state' => 'exists:states'  // 不指定列名则查询states表中的state字段(当前键值对应字段)

unique 数据库验证字段需要不存在

exists相反, unique 要求数据库中不存在验证字段内容。

'state' => 'unique:表名,列名'
'state' => 'unique:states,abbreviation'
'state' => 'unique:states'  // 不指定列名则查询states表中的state字段(当前键值对应字段)

regex:pattern 正则表达式

'state' => 'regex:/^.+@.+$/i'

数组验证

验证必须为数组

'person' => 'array'

验证数组长度必须为 5

'person' => 'array|size:5'

验证数组长度为5到10

'person' => 'array|between:5,10'

验证数组长度大于10

'person' => 'array|min:10'

验证数组长度小于10

'person' => 'array|max:10'

验证数组内容

'person.*.email' => 'email|unique:users'

验证规则汉化文件

<?php
 
return [
 
/*
|--------------------------------------------------------------------------
| Validation Language Lines
|--------------------------------------------------------------------------
|
| The following language lines contain the default error messages used by
| the validator class. Some of these rules have multiple versions such
| as the size rules. Feel free to tweak each of these messages here.
|
*/
 
'accepted'             => ':attribute必须接受',
'active_url'           => ':attribute必须是一个合法的 URL',
'after'                => ':attribute 必须是 :date 之后的一个日期',
'after_or_equal'       => ':attribute 必须是 :date 之后或相同的一个日期',
'alpha'                => ':attribute只能包含字母',
'alpha_dash'           => ':attribute只能包含字母、数字、中划线或下划线',
'alpha_num'            => ':attribute只能包含字母和数字',
'array'                => ':attribute必须是一个数组',
'before'               => ':attribute 必须是 :date 之前的一个日期',
'before_or_equal'      => ':attribute 必须是 :date 之前或相同的一个日期',
'between'              => [
    'numeric' => ':attribute 必须在 :min 到 :max 之间',
    'file'    => ':attribute 必须在 :min 到 :max KB 之间',
    'string'  => ':attribute 必须在 :min 到 :max 个字符之间',
    'array'   => ':attribute 必须在 :min 到 :max 项之间',
],
'boolean'              =>':attribute字符必须是 true 或false, 1 或 0 ',
'confirmed'            => ':attribute 二次确认不匹配',
'date'                 => ':attribute 必须是一个合法的日期',
'date_format'          => ':attribute 与给定的格式 :format 不符合',
'different'            => ':attribute 必须不同于 :other',
'digits'               => ':attribute必须是 :digits 位.',
'digits_between'       => ':attribute 必须在 :min 和 :max 位之间',
'dimensions'           => ':attribute具有无效的图片尺寸',
'distinct'             => ':attribute字段具有重复值',
'email'                => ':attribute必须是一个合法的电子邮件地址',
'exists'               => '选定的 :attribute 是无效的.',
'file'                 => ':attribute必须是一个文件',
'filled'               => ':attribute的字段是必填的',
'image'                => ':attribute必须是 jpeg, png, bmp 或者 gif 格式的图片',
'in'                   => '选定的 :attribute 是无效的',
'in_array'             => ':attribute 字段不存在于 :other',
'integer'              => ':attribute 必须是个整数',
'ip'                   => ':attribute必须是一个合法的 IP 地址。',
'json'                 => ':attribute必须是一个合法的 JSON 字符串',
'max'                  => [
    'numeric' => ':attribute 的最大长度为 :max 位',
    'file'    => ':attribute 的最大为 :max',
    'string'  => ':attribute 的最大长度为 :max 字符',
    'array'   => ':attribute 的最大个数为 :max 个.',
],
'mimes'                => ':attribute 的文件类型必须是 :values',
'min'                  => [
    'numeric' => ':attribute 的最小长度为 :min 位',
    'file'    => ':attribute 大小至少为 :min KB',
    'string'  => ':attribute 的最小长度为 :min 字符',
    'array'   => ':attribute 至少有 :min 项',
],
'not_in'               => '选定的 :attribute 是无效的',
'numeric'              => ':attribute 必须是数字',
'present'              => ':attribute 字段必须存在',
'regex'                => ':attribute 格式是无效的',
'required'             => ':attribute 字段是必须的',
'required_if'          => ':attribute 字段是必须的当 :other 是 :value',
'required_unless'      => ':attribute 字段是必须的,除非 :other 是在 :values 中',
'required_with'        => ':attribute 字段是必须的当 :values 是存在的',
'required_with_all'    => ':attribute 字段是必须的当 :values 是存在的',
'required_without'     => ':attribute 字段是必须的当 :values 是不存在的',
'required_without_all' => ':attribute 字段是必须的当 没有一个 :values 是存在的',
'same'                 => ':attribute和:other必须匹配',
'size'                 => [
    'numeric' => ':attribute 必须是 :size 位',
    'file'    => ':attribute 必须是 :size KB',
    'string'  => ':attribute 必须是 :size 个字符',
    'array'   => ':attribute 必须包括 :size 项',
],
'string'               => ':attribute 必须是一个字符串',
'timezone'             => ':attribute 必须是个有效的时区.',
'unique'               => ':attribute 已存在',
'url'                  => ':attribute 无效的格式',
 
/*
|--------------------------------------------------------------------------
| Custom Validation Language Lines
|--------------------------------------------------------------------------
|
| Here you may specify custom validation messages for attributes using the
| convention "attribute.rule" to name the lines. This makes it quick to
| specify a specific custom language line for a given attribute rule.
|
*/
 
'custom' => [
    'attribute-name' => [
        'rule-name' => 'custom-message',
    ],
],
 
/*
|--------------------------------------------------------------------------
| Custom Validation Attributes
|--------------------------------------------------------------------------
|
| The following language lines are used to swap attribute place-holders
| with something more reader friendly such as E-Mail Address instead
| of "email". This simply helps us make messages a little cleaner.
|
*/
 
'attributes' => [
 
],
 
];
?>

发表回复

您的电子邮箱地址不会被公开。 必填项已用 * 标注