代码之家  ›  专栏  ›  技术社区  ›  A. M.

Cakephp isUnique验证不会在一个字段上触发,而是在另一个字段上工作

  •  1
  • A. M.  · 技术社区  · 15 年前

    var $validate = array(
    
        'username' => array(
    
            'isUnique' => array (
    
                'rule' => 'isUnique',
    
                'message' => 'This username already exists.'),
    
            'custom' => array (
    
                'rule' => array('custom', '/^[A-Za-z0-9,\.-_]*$/i'), 
    
                'message' => 'The username can only contain letters, numbers, _, - and .'),
    
            'minLength' => array(
    
                'rule' => VALID_NOT_EMPTY,
    
                'message' => 'You must fill in the username.')          
        ),
    
        'email' => array(
    
            'isUnique' => array (
    
                'rule' => 'isUnique',
    
                'message' => 'This email address already exists in our database.'),
    
            'valid' => array (
    
                'rule' => array('email', false),
    
                'message' => 'Invalid email.'),
    
            'minLength' => array(
    
                'rule' => VALID_NOT_EMPTY,
    
                 'message' => 'You must fill in the email address.')
    
        )
    
    );
    
    5 回复  |  直到 15 年前
        1
  •  6
  •   jonpa    15 年前

    其他

    SELECT COUNT(*) FROM users WHERE username = 'x' AND username != 'x'
    

    这显然会在测试中返回0或“unique”。修复方法是将主键设置为与正在测试规则的字段不同的值。当您这样做时,SQL转储应该显示如下内容

    SELECT COUNT(*) FROM users WHERE username = 'x' AND key != 'y'
    

        2
  •  3
  •   A. M.    15 年前

    var $validate = array(
        'username' => array(
            'isUnique' => array (
                'rule' => array('checkUniqueUser'),
                'message' => 'This username already exists.'
            )
        )
    )
    
    function checkUniqueUser() {
        return ($this->find('count', array('conditions' => array('User.username' => $this->data['User']['username']))) == 0);
    }
    
        3
  •  1
  •   Haroon    12 年前

    下面是如何在cakephp2.3中使用isUnique赋值规则。假设您有一个字段'username'想要是唯一的,下面的代码就可以做到这一点。

    'username' => array(
    'notempty' => array(
    'rule' => array('notempty'),
    'update' operations
    ),
    'rule' => 'isUnique',
    'message' => 'User alread exists!'
    ),
    
        4
  •  0
  •   Oscar    15 年前

    看看我的用户模型,它看起来是这样的:

    var $validate = array(
        'username' => array(
            'inUse' => array (
                'rule' => array('isUnique', 'username')
            )
        )
    )
    
        5
  •  -1
  •   Maciek    13 年前