如何编写和使用自定义Laravel 5 Validator来验证多个其他字段值

时间:2016-08-19 01:57:19

标签: laravel laravel-5

我有一个表单中的字段只有在其他两个字段设置为特定值时才需要。这不是required_with_all的情况。如果它们被设置,那就不是它,如果它们是专门设置的话。

示例:' foo' => ' required_if_all:巴,2,蝙蝠,1'

我添加了一个服务提供商:

<?php namespace App\Providers;

use Illuminate\Support\ServiceProvider;
use Validator;

class RequiredIfAllProvider extends ServiceProvider {

/**
 * Bootstrap the application services.
 *
 * @return void
 */
public function boot()
{
    Validator::extend('required_if_all', function($attribute,$value,$parameters){

        // Is required if the list of key/value pairs are matching
        $pairs = [];
        foreach($parameters as $kp => $vp) $pairs[$kp] = $vp;
        foreach($pairs as $kp => $vp) if(\Request::input($kp) != $vp) return false;
        return true;

    });
}

/**
 * Register the application services.
 *
 * @return void
 */
public function register()
{
    //
}

}

我确保使用App\Providers\RequiredIfAllProvider;在我的自定义请求文件的顶部。

如果bar和bat都是根据基于验证的参数设置的,则应将新错误添加到错误包中。

我花了很多钱。有什么想法吗?

2 个答案:

答案 0 :(得分:0)

我认为最佳做法是使用the docs中解释的表单请求。

您可以在解释here

的验证中使用required_with_all

答案 1 :(得分:0)

  1. config\app.php下的providers注册服务提供商,无需在请求类中使用它。 (Docs/Registering Providers
  2. 不要从Input门面获取其他属性!这严重限制了验证器的使用,并可能导致奇怪的错误。传递给验证回调的第四个参数是验证器实例。它有getData()方法,为您提供验证程序当前正在验证的所有数据。
  3. 由于您的规则也应该在空值上运行,因此您需要使用extendImplicit()方法进行注册。 (Docs\Custom Validation Rules
  4. 未经测试的示例代码:

    public function boot()
    {
        Validator::extendImplicit('required_if_all', function($attribute, $value, $parameters, $validator) {
            // No further checks required if value is there
            if ($value) {
                return true;
            }
    
            // Convert $parameters into a named array with the attributes as keys
            $n_pairs = floor(count($parameters)/2);
            $pairs = [];
            for ($i = 0; $i < $n_pairs; $i++) {
                $pairs[$parameters[$i]] = $parameters[$i+1];
            }
    
            // Check if all pairs match with the input
            $data = $validator->getData();
            foreach ($pairs as $key => $value) {
                if ($data[$key] !== $value) {
                    // If at least one pair does not match, the rule is always true
                    return true;
                }
            }
    
            // All pairs match, now $value has to be set
            return !!$value;
        });
    }
    
相关问题