作为程序员一定要保持良好的睡眠,才能好编程

为lumen 添加validator验证规则

发布时间:2020-04-03


laravel提供了验证器,有的时候并不能满足我们的需求,因此需要扩展一些自己独有的验证器,应该怎么写?


下面我们来看看:

1、新建App\Components\Validators目录

Components\Validators

这样的目录

并在这里目录下面创建自己的validator类文件


image.png


App\Components\Validators\Validator.php

<?php

namespace App\Components\Validators;

use Illuminate\Support\Facades\Validator as LumenValidator;

class Validator extends LumenValidator
{

    public static function registerCustomValidator()
    {

        /**
         * 新增一个身份证验证功能
         */
        LumenValidator::extend('idCard', function ($attribute, $value, $parameters) {

            //简单一点验证 如果是1 就通过,否则不通过

            if ($value == 1) {
                return true;
            } else {
                return false;
            }

        });

    }


}


第二步、创建 ValidatorServiceProvider.php

image.png

<?php
namespace App\Providers;

use App\Components\Validators\Validator;
use Illuminate\Support\ServiceProvider;


class ValidatorServiceProvider extends ServiceProvider{


    public function boot(){

    }


    public function register()
    {
        Validator::registerCustomValidator();
    }

}



第三步:将ValidatorServiceProvider.php 文件注入到容器中

在bootstrap目录下找到 app.php 后,添加上新建的 ValidatorServiceProvider服务

image.png


以上是默认操作。

我这里是经过封装的,我添加在config目录下 register.php 中:

image.png



提示:validation.id_card  如果出现这样的validation. 这样的提示,一般是因为没有在resources/lang/ 语言包中找到对应的key

image.png

<?php


$vali = Validator::make($request->all(), ['id' => 'required|id_card'], [], ['id' => '序号']);
if ($vali->fails()) {

    echo $vali->errors()->getMessageBag()->first();

}

你看,就是出现 validation.id_card  那么这个 validation 是什么,如何解决????


在resources中创建 lang/en/validation.php 这个文件,

validation.php 文件中的内容怎么来?  

image.png


在本地查找 vendor目录 找到 laravel/lemen-framework/resources/lang/en 这个目录,把 validation.php 内容放在我们新建的文件中即可。

也可以直接复制这个文件,到 /resources/lang/en/ 目录下面

image.png


我们把

//'id_card'                 => 'The :attribute must be a valid.',


这样代码添加上,则重新刷新页面,看看会有什么效果:


image.png



后续事情:如何加入中文? 中文提示语言怎么添加?


在resources目录下 创建 zh_cn 创建 validation.php 

image.png


将验证提示内容放入文件里。

<?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
    | such as the size rules. Feel free to tweak each of these messages.
    |
    */
    'accepted' => ':attribute 必须接受。',
    'active_url' => ':attribute 不是一个有效的网址。',
    '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 必须为布尔值。',
    '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 必须是图片。',
    'in' => '已选的属性 :attribute 非法。',
    'in_array' => ':attribute 没有在 :other 中。',
    'integer' => ':attribute 必须是整数。',
    'ip' => ':attribute 必须是有效的 IP 地址。',
    'json' => ':attribute 必须是正确的 JSON 格式。',
    'max' => [
        'numeric' => ':attribute 不能大于 :max。',
        'file' => ':attribute 不能大于 :max kb。',
        'string' => ':attribute 不能大于 :max 个字符。',
        'array' => ':attribute 最多只有 :max 个单元。',
    ],
    'mimes' => ':attribute 必须是一个 :values 类型的文件。',
    'mimetypes' => ':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' => '当 :other 为 :value 时 :attribute 不能为空。',
    'required_unless' => '当 :other 不为 :value 时 :attribute 不能为空。',
    'required_with' => '当 :values 存在时 :attribute 不能为空。',
    'required_with_all' => '当 :values 存在时 :attribute 不能为空。',
    'required_without' => '当 :values 不存在时 :attribute 不能为空。',
    'required_without_all' => '当 :values 都不存在时 :attribute 不能为空。',
    'same' => ':attribute 和 :other 必须相同。',
    'size' => [
        'numeric' => ':attribute 大小必须为 :size。',
        'file' => ':attribute 大小必须为 :size kb。',
        'string' => ':attribute 必须是 :size 个字符。',
        'array' => ':attribute 必须为 :size 个单元。',
    ],
    'string' => ':attribute 必须是一个字符串。',
    'timezone' => ':attribute 必须是一个合法的时区值。',
    'unique' => ':attribute 已经存在。',
    'uploaded' => ':attribute 上传失败。',
    'url' => ':attribute 格式不正确。',
    'uuid' => ':attribute 格式不正确。',
    'id_card' => ':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' => [
        //'name' => '名称',
        //'username' => '用户名',
        //'email' => '邮箱',
        //
    ],
];











最后一步:打开 .env 文件,将en 改成  zh_cn 即可



APP_LOCALE=zh_cn

image.png


image.png



原理:config/app.php 读取的env 文件,key 是 APP_LOCALE 


这个函数可以读取lang/目录下所有文件的key的值

echo trans('validation.id_card');


现在运行一下项目,就是中文验证了。


image.png

$vali = Validator::make($request->all(), ['id' => 'required|id_card'], [], ['id' => '身份证']);
if ($vali->fails()) {

    echo $vali->errors()->getMessageBag()->first();

}




$rules = [
    'type' => "required_with:name|integer|in:1,2,3",
    'name' => "required_if:type,eee,bbb",
    'time' => "sometimes|string",
    'status' => 'sometimes|integer|in:1,2,3',
    'result' => 'sometimes|integer|in:1,2',
    'deviceSource' => 'sometimes|integer|in:1,2,3',
    'page' => 'sometimes|integer',
];

$messages = [
    'name.required_if' => '请选择您要查询的类型!',
    'type.required_with' => '请输入您要查询的内容'
];

$customAttributes = [
    'type' => '查询类型',
    'name' => '查询内容',
    'time' => '时间范围',
];













也可以参考:

https://www.jianshu.com/p/f44c16221cfe