验证规则和功能

时间:2012-06-14 08:03:22

标签: validation cakephp model cakephp-2.0 cakephp-2.1

我在模型中有一个cakephp 2.1验证规则

 'name' => array(

                'empty' => array(
                  'rule' => 'notEmpty',
                  'required' => true,
                  'allowEmpty' => false,
                  'message' => 'Name is required.'
                ),
                'unique' => array(
                'rule' => 'checkUnique',
                'required' => true,
                'allowEmpty' => false,
                'message' => 'Name already exists.'
                )
              )

我为te checkUnique方法提供了以下代码:

  public function checkUnique($data)
  {
//App::import('Model','User');
// $this->User = & new User();


if(empty($this->data['TeacherLocation']['id']))
{
    $locationInfo = $this->find
    (
        'all',
        array
        (
            'conditions'=>array
            (
                'user_id' => $this->data['TeacherLocation']['user_id'],
                'name' => $this->data['TeacherLocation']['name']
            ),
            'recursive' => -1
        )
    );

    return (empty($locationInfo));

但是我无法找到索引user_id时出现错误。是什么给了什么?

2 个答案:

答案 0 :(得分:0)

所以基本上你想根据其他字段检查isUnique,对吧?

尝试我的validateUnique方法: https://github.com/dereuromark/tools/blob/2.0/Lib/MyModel.php#L818

所以你得到了:

     'name' => array(
         ...
         'unique' => array(
            'rule' => array('validateUnique', array('user_id')),
            'required' => true,
            'allowEmpty' => false,
            'message' => 'Name already exists.'
         )
      )

您的问题似乎是即使您传递的数据中没有user_id,您的验证方法也会被触发。

答案 1 :(得分:0)

isUnique已经内置了蛋糕:

'name' => array(
    'isUnique' => array(
        'rule' => array('isUnique'),
        'message' => 'Name already exists',
    ),