一个完整的使用实例:(验证模型数据)
use PhalconMvcModel;
use PhalconMvcModelValidatorEmail as EmailValidator;
use PhalconMvcModelValidatorUniqueness as UniquenessValidator;
class Users extends Model
{
//定义验证规则
public function validation()
{
$this->validate(new EmailValidator(array(
'field' => 'email',
'message' => '邮箱无效'
)));
$this->validate(new UniquenessValidator(array(
'field' => 'email',
'message' => '对不起,该邮箱已注册'
)));
$this->validate(new UniquenessValidator(array(
'field' => 'username',
'message' => '对不起,该用户名已被占用'
)));
if($this->validationHasFailed() == true) {
return false;
}
}
}
也可以用于验证非模型数据:
use PhalconValidation;
use PhalconValidationValidatorEmail;
use PhalconValidationValidatorPresenceOf;
$validation = new Validation();
$validation->add('email', new Email(array(
'message' => 'The e-mail is not valid'
)));
$messages = $validation->validate($_POST);
if (count($messages)) {
foreach ($messages as $message) {
echo $message, '<br>';
}
}
过滤数据:
$validation->setFilters('name', 'trim');
$validation->setFilters('email', 'trim');
验证事件:
public function beforeValidation($data, $entity, $messages)
public function afterValidation($data, $entity, $messages)
(事件函数中若返回了false,验证就会终止)
取消验证:
$validation->add('telephone', new PresenceOf(array(
'message' => 'The telephone is required',
'cancelOnFail' => true
)));
(若验证失败终止后面的所有验证)