2011-10-23 61 views
3

我正在處理包含用戶數據的表單,特別是電話號碼字段。電話號碼通常不是必需的,因此模型中唯一的驗證規則是usphone規則。但是,如果用戶提交此表單,則電話號碼變得有必要。我認爲我可以簡單地添加一個validate規則,設置模型並調用validates方法,但要麼我做錯了,要麼不按我期望的方式工作。即時更改驗證規則

在我的控制器:

# Update a few validation rules that are specific to this context 
$this->Proposal->Requestor->validate['phone_number']['notempty'] = array(
    'rule'  => 'notEmpty', 
    'message' => 'Please enter a phone number so can can contact you with any questions about the work.', 
    'allowEmpty' => false, 
    'required' => true, 
); 

$validationErrors = array(); 
$this->Proposal->Requestor->set($this->data['Requestor']); # $this->data['Requestor']['phone_number'] only (no other requestor data) 
if(!$this->Proposal->Requestor->validates(array('fieldList' => array('phone_number')))) { 
    $validationErrors['Requestor'] = $this->Proposal->Requestor->validationErrors; 
} 

未報告錯誤,即使我留下的電話號碼字段爲空。在這種情況下,我向用戶請求的唯一信息就是他們的電話號碼,因此Requestor數據的其餘部分爲空,但我已嘗試合併剩餘的用戶數據,並得到相同的結果。如果我刪除了fieldList選項,則會在其他字段中出現錯誤,但空白電話號碼上仍然沒有任何錯誤。

任何想法我在這裏失蹤?我幾個小時都在用這種方式瞎搞,我只是沒有找到正確的答案。

謝謝。

回答

2

該解決方案最終是雙重的:phone_number場,迫使值是一個美國的電話號碼

  1. 我現有的規則。該規則還將allowEmpty設置爲truerequiredfalse。我想獲得一個空值,以便能夠顯示一個特別精確的信息。
  2. 我不得不更新現有的規則來翻轉allowEmptyrequired的值,並添加一個新規則,其last值設置爲true

最後的變化,在我的控制器操作添加如下:

$this->Proposal->Requestor->validate = Set::merge(
    $this->Proposal->Requestor->validate, 
    array(
    'phone_number' => array(
     'notempty' => array(
     'rule'  => 'notEmpty', 
     'message' => 'Please enter a phone number so can can contact you with any questions about the work.', 
     'allowEmpty' => false, 
     'required' => true, 
     'last'  => true, 
    ), 
     'usphone' => array(
     'allowEmpty' => false, 
     'required' => true, 
    ), 
    ) 
) 
); 

我不記得我是否證實,鑑於last值的變化對現有usphone規則是絕對必要的新的規則,但這個組合工作正常。

+0

非常感謝解決了我的問題。 – Vins