在Laravel 5中使用表单请求验证时如何添加自定义验证规则 [英] How add Custom Validation Rules when using Form Request Validation in Laravel 5

查看:126
本文介绍了在Laravel 5中使用表单请求验证时如何添加自定义验证规则的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用表单请求验证方法来验证laravel 5中的请求.我想使用表单请求验证方法添加我自己的验证规则.我的请求类如下所示.我想添加带有字段项的自定义验证数字数组.

I am using form request validation method for validating request in laravel 5.I would like to add my own validation rule with form request validation method.My request class is given below.I want to add custom validation numeric_array with field items.

  protected $rules = [
      'shipping_country' => ['max:60'],
      'items' => ['array|numericarray']
];

我的自定义功能在下面给出

My cusotom function is given below

 Validator::extend('numericarray', function($attribute, $value, $parameters) {
            foreach ($value as $v) {
                if (!is_int($v)) {
                    return false;
                }
            }
            return true;
        });

如何在laravel5中将这种验证方法与表单请求验证一起使用?

How can use this validation method with about form request validation in laravel5?

推荐答案

像您一样使用Validator::extend()实际上非常好,您只需将其放在

Using Validator::extend() like you do is actually perfectly fine you just need to put that in a Service Provider like this:

<?php namespace App\Providers;

use Illuminate\Support\ServiceProvider;

class ValidatorServiceProvider extends ServiceProvider {

    public function boot()
    {
        $this->app['validator']->extend('numericarray', function ($attribute, $value, $parameters)
        {
            foreach ($value as $v) {
                if (!is_int($v)) {
                    return false;
                }
            }
            return true;
        });
    }

    public function register()
    {
        //
    }
}

然后通过将提供者添加到config/app.php的列表中来注册提供者:

Then register the provider by adding it to the list in config/app.php:

'providers' => [
    // Other Service Providers

    'App\Providers\ValidatorServiceProvider',
],

您现在可以在任意位置使用numericarray验证规则

You now can use the numericarray validation rule everywhere you want

这篇关于在Laravel 5中使用表单请求验证时如何添加自定义验证规则的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆