开发者

CakePHP - Validation rule has syntax error I can't see

I'm getting Parse error: syntax error, unexpected T_VARIABLE, expecting ')' on the line commented below. Can开发者_如何学运维't for the life of me figure out why it's throwing this error.

public $validate = array(
    'password1' => array(
        'rule1' => array('rule' => 'alphaNumeric', 'message' => 'Your password should only contain alphanumeric characters.'),
        'rule2' => array('rule' => '/\d/', 'message' => 'Your password must contain at least one numeric character.'),
        'rule3' => array('rule' => '/^(?=.*?[A-Z])(?=.*?[a-z])/', 'message' => 'Your password must contain at least one uppercase and one lowercase letter.'),
        'rule4' => array('rule' => array('minLength', 8), 'message' => 'Your password must be at least 8 characters long.'),
    ),
    'password2' => array(
        // ERROR ON LINE BELOW
        'rule' => array('_passwordsMatch', $this->data['PasswordReset']['password2']),
        'message' => 'The passwords you entered do not match.'
    )
);

/**
 * Custom validation method to check that the entered passwords match
 *
 * @param  string $password1
 * @param  string $password2
 * @return bool
 */
protected function _passwordsMatch($password1, $password2) {
    return ($password1 === $password2);
}

As you can see I'm trying to make a custom validation rule to check the two passwords coming from the user's submitted form. Related question would be is this the wrong way to be trying to pass the other field value to the custom rule?


You are not allowed to reference $this during the initialization syntax of a class property. If you really need that, you must move the array definition to the class constructor.

Quoting the Documentation:

[Properties] are defined by using one of the keywords public, protected, or private, followed by a normal variable declaration. This declaration may include an initialization, but this initialization must be a constant value--that is, it must be able to be evaluated at compile time and must not depend on run-time information in order to be evaluated.

This rule is enforced at compile time, so there are grammar rules for static array() syntax that do not allow arbitrary expressions. This is why you get a syntax error: Instead of $this, the parser expects a ) that closes array(.


funny how this comes up this often right now check out CakePHP validation rule to match field1 and field2 for a clean behavior approach on this subject (see my answer)

also note: your alphanumeric rule is out of line in my opinion. you should never force a user to use less chars then he wants in a password field. many users use at least some special char and DONT use your upper or lower case style. i think you are restricting the user more than needed.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜