2016-08-19 28 views
0

我有一个窗体中的字段只有在设置了其他两个字段时才是必需的。这不是required_with_all的情况。如果它们被设置,那么它不是它的,如果它们是专门设置的。如何编写和使用自定义的Laravel 5验证器来验证多个其他字段值

实施例:'富'=> '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均基于基于验证的参数进行设置,则应在错误包中添加新的错误。

我在这方面花了不少。有任何想法吗?

+0

只要看看登录控制器。 laravel 5起,我认为他们把auth转移到了'特性',只是在那里添加了你需要的值。 – Gokigooooks

+0

这和登录或认证没有任何关系。目标是一个网站范围的可用验证规则。 –

+0

对不起,我很在意验证。无论如何,在laravel 5.1中,您可以使用特征将独特的一组函数和变量应用于控制器。你可以在那里添加你的验证,所以你可以在任何地方注入 – Gokigooooks

回答

0
  1. 注册在config\app.php服务提供商providers下,没有必要在请求类使用它。 (Docs/Registering Providers
  2. 不要从Input正面获得其他属性!这大大限制了验证器的使用,并可能导致一些奇怪的错误。传递给验证回调的第四个参数是验证器实例。它有一个getData()方法,为您提供验证器当前正在验证的所有数据。
  3. 由于您的规则也应该在空值上运行,您需要使用extendImplicit()方法进行注册。 (Docs\Custom Validation Rules

未测试实例代码:

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; 
    }); 
} 
0

我相信最好的做法是使用表格请求,如the docs中所述。

你也可以使用required_with_all和在等作为验证解释here

+0

使用L5而不是5.1。我也为此使用自定义表单请求。在这种情况下,Required_with_all不起作用。 –