2

我正在使用 Model::validation() 调用进行模型验证。

看起来 Model::validate() 只接受来自Phalcon\Mvc\Model\Validator命名空间的验证器,并且在使用Phalcon\Validation\Validator时崩溃:

class User extends Phalcon\Mvc\Model
{
    protected $email = 'invalid @email.*';

    public function validation()
    {
        // Validator from Model namespace
        $this->validate(new Phalcon\Mvc\Model\Validator\Uniqueness(array(
            "field"   => "email",
            "message" => "The email is already registered"
        )));

        // Validator from Validation namespace - causes "BadMethodCallException" - "Wrong number of parameters".
        $this->validate(new Phalcon\Validation\Validator\Between(array(
            "field"   => "counter",
            'minimum' => 10,
            'maximum' => 20,
            "message" => "Invalid value"
        )));   

        $validationHasFailed = $this->validationHasFailed();
        return $validationHasFailed != true;
    }
}

这会导致BadMethodCallException - Wrong number of parameters错误。

我的下一个想法是更改代码如下:

class User extends Phalcon\Mvc\Model
{
    protected $email = 'invalid @email.*';

    public function validation()
    {
        // Omitting Uniqueness validator.

        $validation = new Phalcon\Validation();
        $validation->add('email', new Phalcon\Validation\Validator\Email);
        $this->validate($validation);

        $validationHasFailed = $this->validationHasFailed();
        return $validationHasFailed != true;
    }
}

但是,该代码无法检测到电子邮件字段的无效值(不会发生验证错误)。

同时,以下电子邮件验证按预期工作:

$validation = new Validation();
$validation->add('email', new EmailValidator());
$messages = $validation->validate([
    'email' => 'bad email @...',
], 'email');

问题:

我可以在 Model::validation() 调用中使用非模型验证器吗?

谢谢!

4

1 回答 1

9

好吧,我的问题的答案是否定的。

这是一个解决方法:

public function validation()
{
    /**
     * Validate email address.
     *
     * Looks like there's a difference between model- and non-model validators.
     */
    $emailField = 'email';
    $validation = new Phalcon\Validation;
    $validation->add($emailField, new Phalcon\Validation\Validator\Email);

    /**
     * @var Phalcon\Validation\Message\Group
     */
    if (sizeof($messages = $validation->validate([
        $emailField => $this->email,
    ], $emailField))) {
        $message = new Phalcon\Mvc\Model\Message('Invalid email address.', $emailField);
        $this->appendMessage($message);
    } else {
        /**
         * Only when non-model validators don't fail, get on with model validators
         *
         * Validate email uniqueness.
         */
        $this->validate(new Phalcon\Mvc\Model\Validator\Uniqueness([
            'field' => $emailField,
            'message' => 'The email is already registered'
        ]));

    }
    $validationHasFailed = $this->validationHasFailed();

    return $validationHasFailed != true;
}

希望有人觉得这很有用。

于 2013-09-30T20:10:25.350 回答