Phalcon\Mvc\Model::validation()和非模型验证器[英] Phalcon\Mvc\Model::validation() and non-model validators

问题描述

我正在使用 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 - 参数数量错误错误.

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

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() 调用中使用非模型验证器吗?

谢谢!

推荐答案

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

这里有一个解决方法:

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;
}

希望有人觉得这很有用.

本文地址:https://www.itbaoku.cn/post/1739776.html