1

我将 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
    }
}
4

1 回答 1

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"] is my User table via KnpRepositoryServiceProvider
  • $app["user"]->findByEmail returns null or a user record
于 2012-10-07T20:03:21.463 回答