2010-01-07 77 views
0

即时进行自定义验证,但在无效时不会显示错误消息。 你知道问题在哪里吗?我认为这个问题可能在无效函数中。你知道如何设置它为这样的嵌套验证吗?在模型cakephp自定义验证不会在嵌套规则中显示错误消息

var $validate = array(
    'receiver' => array(
     'maxMsg' => array(
      'rule' => array('maxMsgSend'), 
      //'message' => '' 
      ), 
     'notEmpty' => array(
      'rule' => array('notEmpty'), 
      'message' => 'field must not be left empty' 
      ))...... 

自定义的验证方法:

​​

UPDATE:如何解决它。 我将该函数的内容移至模型中的beforeValidate()。

function beforeValidate($data) { 
    if (isset($this->data['User']['receiver'])) 
    { 
      $id = User::$auth['User']['id']; 

      $count_contacts = (int)$this->Contact->find('count', array('conditions' =>array('and' =>array( 'Contact.contact_status_id' => '2', 
                   'Contact.user_id' => $id)))); 

      $current_credit = (int)$this->field('3_credit_counter', array('id' => $id)); 
      $max_allowed_messages = ($count_contacts >= $current_credit)? $current_credit: $count_contacts ; 


      if ($data>$max_allowed_messages) 
      { 
       $this->invalidate('receiver', "you can send maximum of {$max_allowed_messages} text messages."); 
       return false; 
      } 
    } 
    return true; 
} 

回答

0

我想你maxMsgSend功能仍需如果验证失败,返回false。

+0

实际上它出现了一个错误消息,说maxMsg,即使在我从无效函数中删除maxMsg之后。 它似乎是从嵌套数组中获取名称。 – ondrobaco 2010-01-07 15:20:05

0

我认为问题出在您的Model :: maxMsgSend函数中。写在面包店,(http://bakery.cakephp.org/articles/view/using-equalto-validation-to-compare-two-form-fields),建立一个自定义的验证规则(他们想比较两个领域,但其概念是相同的),他们写道:

我返回一个错误,如果值穿上” t匹配,如果他们这样做是真的。

检查了他们的模型类代码,大约下降一半。简而言之,您不需要在自定义验证方法中调用invalidate;如果它通过验证,则返回true;如果未通过验证,则返回false。

+0

那是真的,我使用无效的主要原因是向用户显示自定义错误消息。如果我只是返回false ..错误消息将defoult为静态消息 – ondrobaco 2010-01-07 23:38:11

+0

您可以不在您的Model :: validation属性中的消息索引设置错误消息? – 2010-01-08 13:44:16

+0

我可以但它会是一个静态消息,它不会插入max_allowed_messages的值 – ondrobaco 2010-01-08 13:54:40