没错,实现中缺少 getMessages() 方法。现在你可以在它被正式添加到 C 类时将它添加到你的模型中:
<?php
class Users extends Phalcon\Mvc\Collection
{
public function getMessages()
{
return $this->_errorMessages;
}
}
1-如何显示验证结果的错误消息?检查上面
2-如何创建自定义验证器?
验证器是从“Phalcon\Mvc\Model\Validator”继承并实现“Phalcon\Mvc\Model\ValidatorInterface”的类:
<?php
use Phalcon\Mvc\Model\Validator,
Phalcon\Mvc\Model\ValidatorInterface;
class HashValidator extends Validator implements ValidatorInterface
{
public function validate($record)
{
$fieldName = $this->getOption('field');
if (!preg_match('/[a-z]+/', $fieldName) {
$this->appendMessage("The hash is not valid", $fieldName, "Hash");
return false;
}
return true;
}
}
如果您不想重用验证器,您可以简单地向模型添加验证规则:
<?php
use Phalcon\Mvc\Model\Message;
class Users extends Phalcon\Mvc\Collection
{
public function validation()
{
if (!preg_match('/[a-z]+/', $this->password) {
$this->_errorMessages[] = new Message("The hash is not valid", "password", "Hash");
return false;
}
return true;
}
public function getMessages()
{
return $this->_errorMessages;
}
}
3- Phalcon\Mvc\Model\Validator\Uniqueness 验证器 NOSQL 是否兼容?此验证器仅与 SQL 模型兼容,但是,您可以通过以下方式创建验证器来处理 NoSQL 集合:
<?php
use Phalcon\Mvc\Model\Validator,
Phalcon\Mvc\Model\ValidatorInterface;
class UniqueValidator extends Validator implements ValidatorInterface
{
public function validate($record)
{
$field = $this->getOption('field');
if ($record->count(array("field" => $record->readAttribute($field)))) {
$this->appendMessage("The ".$field." must be unique", $fieldName, "Unique");
return false;
}
return true;
}
}