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

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

问题描述

我正在使用表单请求验证方法来验证 Laravel 5 中的请求.我想使用表单请求验证方法添加我自己的验证规则.下面给出了我的请求类.我想添加带有字段项的自定义验证 numeric_array.

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']
];

我的自定义函数如下

 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 AppProviders;

use IlluminateSupportServiceProvider;

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

    'AppProvidersValidatorServiceProvider',
],

您现在可以在任何地方使用 numericarray 验证规则

You now can use the numericarray validation rule everywhere you want

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

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