我正在使用Model :: validation()调用进行模型验证。
看起来Model :: validate()只接受来自 Phalcon \ Mvc \ Model \ Validator 命名空间的验证器,并在使用 Phalcon \ Validation \ Validator 时崩溃:< / p>
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()调用中使用非模型验证器吗?
谢谢!
答案 0 :(得分: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;
}
希望有人觉得这很有用。