我使用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
}
}
我看到你已经切换至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或用户记录