2010-06-30 98 views
1

我正在嘗試使用cakephp模型實現表單驗證。這裏是我的代碼片段...Cakephp中的模型驗證問題

型號

// File: /app/models/enquiry.php 
class Enquiry extends AppModel { 
    var $name = "Enquiry"; 
    var $useTable = false; 
    var $_schema = array(
     "name"  => array("type" => "string", "length" => 100), 
     "phone"  => array("type" => "string", "length" => 30), 
     "email"  => array("type" => "string", "length" => 255) 
    ); 
    var $validate = array(
     "name" => array(
      "rule" => array("minLength" => 1), 
      "message" => "Name is required" 
     ), 
     "email" => array(
      "emailFormat" => array("rule" => "notEmpty", "last" => true, "message" => "Email is required"), 
      "emailNeeded" => array("rule" => array("email", true), "message" => "Must be a valid email address") 
     ) 
    ); 
} 

控制器動作

// /app/controllers/nodes_controller.php 
class NodesController extends AppController { 

    var $name = "Nodes"; 
    var $uses = array("Enquiry"); 
    function enquire() { 
     if ($this->data) { 
     $this->Enquiry->set($this->data); 
     $this->Enquiry->set("data", $this->data); 
     if ($this->Enquiry->validates(
       array("fieldList" => array("name", "email")) 
      )) { 
      // ..... 
      } 
     } 
    } 
} 

查看....

// /app/views/nodes/enquire.ctp 
<?php echo $form->create("Node", array("action" => "ask")); ?> 
<?php echo $form->input("name", array("label" => "Name")); ?> 
<?php echo $form->input("email", array("label" => "Email")); ?> 
<?php echo $form->input("phone", array("label" => "Phone")); ?> 
<?php echo $form->end("Send");?> 

我的問題:在提交時,表單從不驗證。即使我沒有在表單中輸入任何內容,validate函數也會每次都返回true。

我在做什麼錯?

Regards

回答

1

當你只有兩個驗證規則是沒有意義的,列出在validates()要驗證這兩個領域。試試這個方法:

function enquire(){ 
    if($this->data){ 
     $this->Enquiry->set(this->data); 
     if($this->Enquiry->validates()){ 
      // it validated logic 
     }else{ 
      // didn't validate logic 
     } 
    } 
} 

您的驗證陣列應該是(遵循語法一致性):

var $validate = array(
    'name' => array(
     'notEmpty' => array(
      'rule' => 'notEmpty', 
      'message' => 'Name is required' 
     ) 
    ), 
    'email' => array(
     'emailFormat' => array(
      'rule' => 'notEmpty', 
      'message' => 'Email is required' 
     ), 
     'emailNeeded' => array(
      'rule' => array('email', true), 
      'message' => 'Must be a valid email address' 
     ) 
    ) 
); 
+0

這並不工作。現在我看到$ this-> Model-> validates()返回false,但我仍然看不到出現的錯誤消息。我需要在我的模型中使用invalidate()方法嗎? – vikmalhotra 2010-07-01 01:54:52

+0

我剛剛檢查了invalidFields數組,它在那裏顯示無效字段。但是錯誤信息並沒有以形式出現...... – vikmalhotra 2010-07-01 02:02:14

+0

這很奇怪。嘗試'$ form-> error('email');' – bancer 2010-07-01 02:56:41

1

我認爲你的錯誤數據傳入驗證。將其具有$this->data我只想叫

$this->Model->validates(); 
// or 
$this->Model->validates($this->data);