我有一个实体和 validations.yml ...用于在实体(表格)中注册新记录我有一个唯一电子邮件的规则并且工作正常但是当我尝试通过电子邮件和密码进行简单登录时,以及 $ form-> isValid()的传递时,我不想显示有关已经收到的电子邮件的消息而不是我想跳过这条规则或只是比较电子邮件和密码,只比较电子邮件是空的还是密码。
或者是否存在一种即时添加验证的方法。
提前谢谢!
答案 0 :(得分:2)
是的,您可以使用Symfony验证器服务“即时验证”。在Symfony validation文档中对此进行了相当清楚的解释。例如:
$author = new Author();
// ... do something to the $author object
$validator = $this->get('validator');
$errors = $validator->validate($author);
return (count($errors) > 0) ? new Response('Some Error Message') : new Response('Some Success Message');
您甚至可以告诉它您要验证哪些字段。如果您可以发布实际代码以及您遇到的具体问题,我可以尝试提供更具体的答案。
要仅在控制器操作中验证表单中的特定字段:
use Symfony\Component\Validator\Constraints\Email;
...
$emailConstraint = new Email();
// all constraint "options" can be set this way
$emailConstraint->message = 'Invalid email address';
// use the validator to validate the value
$errorList = $this->get('validator')->validateValue(
$email,
$emailConstraint
);
if (count($errorList) == 0) {
// this IS a valid email address, do something
} else {
// this is *not* a valid email address
$errorMessage = $errorList[0]->getMessage();
// ... do something with the error
}
答案 1 :(得分:0)
您想要的是验证组。 symfony.com/doc/current/book/forms.html#validation-groups
虽然我个人只是创建不同的表单类型并将验证器直接应用于表单元素。