簡體   English   中英

Laravel-兩個輸入值都不能沒有如何驗證?

[英]Laravel - both input values can't be no how to validate?

我正在將Laravel用於一個項目,並且想知道如何驗證我面臨的特定場景。 如果可能的話,我想使用Laravel的本機功能來做到這一點?

我有一個包含兩個問題(作為下拉菜單)的表格,對於這兩個問題,答案都可以是或否,但是,如果兩個下拉菜單均等於“否”,則它應該引發驗證錯誤,但它們都可以是。

我已經查看了laravel文檔,但是不確定如果可以使用一個規則,那么在這里適用什么規則? 在這種情況下,我需要編寫自己的規則嗎?

很簡單:

假設兩個字段名稱分別為foobar

然后:

 // Validate for those fields like $rules = ['foo'=>'required', 'bar'=>'required'] etc

 // if validation passes, add this (i.e. inside if($validator->passes()))

 if($_POST['foo'] == 'no' && $_POST['bar'] == 'no')
 {
     $messages = new Illuminate\Support\MessageBag;
     $messages->add('customError', 'both fields can not be no');
     return Redirect::route('route.name')->withErrors($validator);
 }

檢索時會出現錯誤信息。

如果您感到困惑,只需轉儲$error變量並檢查如何檢索它。 即使驗證通過但在上面的代碼中失敗了,也不會與驗證確實失敗的情況有所不同。

顯然不知道您的表單字段是什么,但這應該可行。

這是使用others()方法添加條件查詢的,如果相應的字段等於no,則字段值不應為no。

    $data = array(
        'field1' => 'no',
        'field2' => 'no'
    );

    $validator = Validator::make($data, array());
    $validator->sometimes('field1', 'not_in:no', function($input) {
        return $input->field2 == 'no';
    });
    $validator->sometimes('field2', 'not_in:no', function($input) {
        return $input->field1 == 'no';
    });

    if ($validator->fails()) {
        // will fail in this instance
        // changing one of the values in the $data array to yes (or anything else, obvs) will result in a pass
    } 

請注意,這僅適用於Laravel 4.2+

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM