我正在使用Silex进行一个小项目,但我不确定如何验证两个匹配的密码字段,还要检查使用数据库连接的电子邮件的唯一性。我无法在SF2文档中找到它。
可能有人可以给我一个提示或样品吗?
提前致谢
if ('POST' === $user->getMethod()) {
$constraint = new Assert\Collection(array(
'name' => array(new Assert\NotBlank(array('message' => 'Name shouldnt be blank'))),
'username' => array(new Assert\NotBlank(), new Assert\MinLength(3)),
'email' => array(new Assert\NotBlank(), new Assert\Email()),
'password' => array(new Assert\NotBlank(), new Assert\MinLength(6)),
'password2' => array(new Assert\NotBlank(), new Assert\MinLength(6)),
'terms' => array(new Assert\True()),
));
$errors = $app['validator']->validateValue($user->request->all(), $constraint);
if (!count($errors)) {
//do something
}
}
答案 0 :(得分:5)
我在评论中看到您已经切换到Sf2表单。我猜您找到了RepeatedType
字段,该字段最适合注册表单的重复密码字段 - 它有一个内置的检查来验证这两个值是否匹配。
您的另一个问题是检查电子邮件地址的唯一性。这是我的注册表的相关部分:
<?php
namespace Insolis\Form;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolverInterface;
use Symfony\Component\Validator\Constraints as Assert;
use Symfony\Component\Validator\ExecutionContext;
class RegisterType extends AbstractType
{
public function buildForm(FormBuilderInterface $builder, array $options)
{
$app = $options["app"];
$builder->add("email", "email", array(
"label" => "E-mail address",
"constraints" => array(
new Assert\NotBlank(),
new Assert\Email(),
new Assert\Callback(array(
"methods" => array(function ($email, ExecutionContext $context) use ($app) {
if ($app["user"]->findByEmail($email)) {
$context->addViolation("Email already used");
}
}),
)),
),
));
}
public function setDefaultOptions(OptionsResolverInterface $resolver)
{
parent::setDefaultOptions($resolver);
$resolver->setRequired(array("app"));
}
public function getName()
{
return "register";
}
}
注意:
$app
,因此我可以访问依赖注入容器$app["user"]
是我的用户表KnpRepositoryServiceProvider $app["user"]->findByEmail
返回null或用户记录