laravel5.5验证器

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/bizu005/article/details/82910705

request直接验证
使用 Illuminate\Http\Request 对象提供的 validate 方法来实现这一功能,
如果验证规则通过,代码将会继续往下执行;
反之,如果验证失败,将会抛出一个异常,相应的错误响应也会自动发送给用户。
在这个传统的 HTTP 请求案例中,将会生成一个重定向响应,
如果是 AJAX 请求则会返回一个 JSON 响应。

<?php
    $rule=[
        'id'=>'required',
        'name'=>'required|max:10'
    ];
    $msg=[
        'id.required'=>'id值错误',
        'name.required'=>'name必填',
        'name.max'=>'名称不能超过10个字',
    ];
    $re=request()->validate($rule,$msg);
    //验证不通过则直接跳转首页了

复杂表单请求验证
对于更复杂的验证场景,创建一个“表单请求”。
表单请求是包含验证逻辑的自定义请求类,可以使用 Artisan 命令 make:request:

<?php
#php artisan make:request StoreBlogPost
//编写规则
class StoreBlogPost extends FormRequest{
    public function rules(){
        return [
            'title' => 'required|unique:posts|max:255',
            'body' => 'required',
        ];
    }
}
//使用,在控制器方法中实例化即可
class Blog extends Controller{
    public function store(StoreBlogPost $request){
        /*如果验证失败,重定向响应会被生成并将用户退回上一个位置,
        错误信息也会被存储到一次性 Session 以便在视图中显示。
        如果是 AJAX 请求,带 422 状态码的 HTTP 响应将会返回给用户,
        该响应数据中还包含了 JSON 格式的验证错误信息。*/
    }
}

Validator验证器

<?php
    $rule=[
        'id'=>'required',
        'name'=>'required|max:10'
    ];
    $msg=[
        'id.required'=>'id值错误',
        'name.required'=>'name必填',
        'name.max'=>'名称不能超过10个字',
    ];
    $validator=\Validator::make(request()->input(),$rule,$msg);
    $validator->after(function($validator) {
        $validator->errors()->add('testField', 'Something is wrong with this field!');
    });
    if($validator->fails()){
        dump($validator->errors()->get('testField'));
        dump($validator->errors()->first('id'));
        dump($validator->errors()->toArray());
        dd($validator->errors()->all());
    }

判断验证是否通过并处理验证信息

<?php
if ($validator->fails())
{
    $messages = $validator->messages();
    dump($messages);
    //$messages格式如下
    /*MessageBag {#462 ▼
      #messages: array:3 [▼
        "id" => array:1 [▼
          0 => "id值错误"
        ]
        "name" => array:1 [▼
          0 => "name必填"
        ]
        "testField" => array:1 [▼
          0 => "Something is wrong with this field!"
        ]
      ]
      #format: ":message"
    }*/
    
    echo $messages->first('id');     //获取某个字段的第一个错误信息
    foreach ($messages->get('id') as $message){}   //遍历某个字段的所有错误信息
    foreach ($messages->all() as $message){}      //遍历所有错误信息
    if ($messages->has('id')){}              //判断某个字段是否有错误
    //获取某个字段的错误信息并格式化
    echo $messages->first('id', '<b style="color:red">:message</b>');
    //所有错误信息格式化
    foreach ($messages->all('<li>:message</li>') as $message){}
}

框架自带的验证规则

accepted     //字段值为 yes, on, 或是 1 时,验证才会通过。这在确认"服务条款"是否同意时很有用。
active_url   //字段值通过 PHP 函数 checkdnsrr 来验证是否为一个有效的网址。
after:date   //验证字段是否是在指定日期之后。这个日期将会使用 PHP strtotime 函数验证。
alpha        //字段仅全数为字母字串时通过验证。
alpha_dash   //字段值仅允许字母、数字、破折号(-)以及底线(_)
alpha_num    //字段值仅允许字母、数字
array       //字段值仅允许为数组
before:date //验证字段是否是在指定日期之前。这个日期将会使用 PHP strtotime 函数验证。
between:min,max //字段值需介于指定的 min 和 max 值之间。字串、数值或是文件都是用同样的方式来进行验证
confirmed   //字段值需与对应的字段值 foo_confirmation 相同。
例如,如果验证的字段是 password ,那对应的字段 password_confirmation 就必须存在且与 password 字段相符。
date        //字段值通过 PHP strtotime 函数验证是否为一个合法的日期
date_format:format  //字段值通过 PHP date_parse_from_format 函数验证符合 format 制定格式的日期是否为合法日期
different:field     //字段值需与指定的字段 field 值不同
digits:value    //字段值需为数字且长度需为 value
digits_between:min,max  //字段值需为数字,且长度需介于 min 与 max 之间
boolean     //字段必须可以转换成布尔值,可接受的值为 true, false, 1, 0, "1", "0"
email       //字段值需符合 email 格式
exists:table,column     //字段值需与存在于数据库 table 中的 column 字段值其一相同
image       //文件必需为图片(jpeg, png, bmp, gif 或 svg)
in:foo,bar,...      //字段值需符合事先给予的清单的其中一个值
integer       //字段值需为一个整数值
ip      //字段值需符合 IP 位址格式
max:value       //字段值需小于等于 value。字串、数字和文件则是判断 size 大小
mimes:foo,bar,...       //文件的 MIME 类需在给定清单中的列表中才能通过验证
min:value       //字段值需大于等于 value。字串、数字和文件则是判断 size 大小
not_in:foo,bar,...  //字段值不得为给定清单中其一
numeric     //字段值需为数字
regex:pattern   //字段值需符合给定的正规表示式
required    //字段值为必填
required_if:field,value     //字段值在 field 字段值为 value 时为必填
required_with:foo,bar,...   //字段值 仅在 任一指定字段有值情况下为必填
required_with_all:foo,bar,...   //字段值 仅在 所有指定字段皆有值情况下为必填
required_without:foo,bar,...    //字段值 仅在 任一指定字段没有值情况下为必填
required_without_all:foo,bar,...    //字段值 仅在 所有指定字段皆没有值情况下为必填
same:field  //字段值需与指定字段 field 等值
size:value  //字段值的尺寸需符合给定 value 值。对于字串来说,value 为需符合的字串长度。
对于数字来说,value 为需符合的整数值。对于文件来说,value 为需符合的文件大小(单位 kb)。
timezone    //字段值通过 PHP timezone_identifiers_list 函数来验证是否为有效的时区
unique:table,column,except,idColumn     //字段值在给定的数据库中需为唯一值。
如果 column(字段) 选项没有指定,将会使用字段名称
url     //字段值需符合 URL 的格式

猜你喜欢

转载自blog.csdn.net/bizu005/article/details/82910705