我正在嘗試創建我的自定義驗證,如果選擇了某個選項,則需要客戶 ID。現在,我只想測驗自定義驗證是否有效,所以我不關心選項,只設定訊息并始終回傳 false。由于 MVC 模式的原因,我不想將驗證放在我的控制器中。如果將我的自定義驗證放入模型中,它將不起作用,因此我在名為 MY_Form_validation 的庫檔案夾中創建了一個新的驗證檔案。
MY_Form_validation.php
if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class MY_Form_validation extends CI_Form_validation
{
protected $CI;
function __construct($rules = array())
{
parent::__construct($rules);
}
public function customer_required($str)
{
$this->set_message('customer_required', 'Customer is required if you choose option A');
return false;
}
}
在模型中,我這樣稱呼它:
public function save()
{
/* other form validation */
$this->form_validation->set_rules('customer_id', 'Customer', 'customer_required');
return $this->form_validation->run();
}
我也把它放在自動加載中
$autoload['libraries'] = array('session','database','table','form_validation', 'MY_Form_validation');
它應該總是無法保存,因為驗證只回傳 false。但看起來自定義驗證根本沒有執行,因為它總是回傳 true。有什么我錯過的嗎?已經好幾天了,我仍然不知道我做錯了什么。請幫忙。
更新
正如 Marleen 建議的那樣,我嘗試使用 callable 但同樣,函式 check_customer 似乎沒有執行,因為我有一個成功的保存。
客戶模型
$this->form_validation->set_rules('customer_is_required', array($this->customer_model, 'check_customer'));
$this->form_validation->set_message('customer_is_required', 'Customer is required of you choose option A');
private function check_customer()
{
return false;
}
uj5u.com熱心網友回復:
您的方法沒有被觸發,因為您的customer_id欄位提交為空。Codeigniter 不會驗證空欄位,除非規則是required//isset或matches回呼或可呼叫之一。(見Form_validation.php第 700 行。)
如果您將規則指定為可呼叫,它可以保留在模型中并執行,即使該欄位提交為空:
$this->form_validation->set_rules('customer_id', 'Customer', array(
array($this->your_model, 'customer_required')
));
(另見:https ://codeigniter.com/userguide3/libraries/form_validation.html#callable-use-anything-as-a-rule )
$this->form_validation->set_rules('customer_is_required', 'Customer', array(
array($this->customer_model, 'check_customer')
));
public function check_customer($str) {
return false;
}
要添加訊息,請使用:
$this->form_validation->set_rules('customer_is_required', 'Customer', array(
array('customer_is_required', array($this->customer_model, 'check_customer'))
));
$this->form_validation->set_message('customer_is_required', 'Customer is required of you choose option A');
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/478677.html
標籤:php 代码点火器 codeigniter-form-validation
