2016-09-16 154 views
1

我想驗證validationDefault()函數中的某些字段並非全部是因爲條件,而是沒有找到任何解決方案。CakePHP 3中的條件表單驗證

實施例:

public function validationDefault(Validator $validator) { 

    $validator 
      ->requirePresence('title', 'create') 
      ->notEmpty('title'); 

    $validator 
      ->requirePresence('inquiry') 
      ->allowEmpty('inquiry'); 
    $validator 
      ->requirePresence('dosage') 
      ->allowEmpty('dosage'); 

    $validator 
      ->requirePresence('dosage_occurance') 
      ->integer('dosage_occurance') 
      ->allowEmpty('dosage_occurance'); 

    return $validator; 
} 

注意:從兩個不同勢形式來響應第一含有(標題和查詢)等含有(標題,劑量和dosage_occurance)。 我想從validationDefault()驗證,但它給我的錯誤

"dosage_occurance": { 
    "_required": "This field is required" 
} 

當我不發送dosage_occurance這是正確的,但按條件是錯誤的。 在創建新實體時使用fieldList但它不起作用。

感謝

+0

使用不同的驗證設置http://book.cakephp.org/3.0/en/orm/validation.html#using-a-different-validation-set – Salines

+0

謝謝,是的,我可以用不同的驗證集但我認爲這不是正確的解決方案,fieldList可能是一個解決方案,但沒有發現任何有關該 –

+0

閱讀文檔的問題是什麼? http://book.cakephp.org/3.0/en/core-libraries/validation.html#conditional-validation習慣於閱讀*整個文檔頁面,而不僅僅是片段。它也位於右側的頁面內容列表中。 – burzum

回答

1

你想有條件的驗證。

從文檔摘自:

在定義的驗證規則,可以使用上鍵時應當應用驗證規則來定義。如果未定義,則將始終應用該規則。其他有效的值是創建和更新。使用這些值之一將使該規則適用於僅創建或更新操作。從那裏取

Read the whole documentation page.

例,注意on部分。

$validator->add('picture', 'file', [ 
    'rule' => ['mimeType', ['image/jpeg', 'image/png']], 
    'on' => function ($context) { 
     return !empty($context['data']['show_profile_picture']); 
    } 
]);