我注意到phalcon验证模型将进行验证,无论该字段确实存在于帖子中。
public function validation()
{
$this->validate(new Uniqueness(
array(
"field" => "email",
"message" => "The email is already registered"
)
));
$this->validate(new Email(
array(
"field" => "companyEmail",
"message" => "Email format error"
)
));
return $this->validationHasFailed() != true;
}
在这种情况下,即使用户正在保存其他数据而不是电子邮件,电子邮件字段仍在验证中。如何仅在字段存在时才进行验证? (对于某些领域,每次都不需要验证)
可能像
if( *syntax* ){
$this->validate(new Email(
array(
"field" => "companyEmail",
"message" => "Email format error"
)
));
}
答案 0 :(得分:2)
使用表单类(Phalcon \ Forms \ Form的子类),添加代码以检查beforeValidate函数中是否存在变量,并且只有在设置变量时才添加验证器。
function beforeValidation($data, $entity)
{
...
$elements = $this->getElements();
if (isset($data['fieldname'])) {
$elements['fieldname']->addValidator(new Email(
array(
"field" => "companyEmail",
"message" => "Email format error"
)
))
...
}
}
答案 1 :(得分:0)
这是我的解决方案:
if( !empty($this-companyEmail) ){
$this->validate(new Email(
array(
"field" => "companyEmail",
"message" => "Email format error"
)
));
}
我这样做是因为我通过ajax传递变量