2016-08-19 37 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不起作用。 –