问题
I'm using Silex for a small project, but I'm not sure how to validate two matching password fields, also check for the uniqueness of an email using a database connection. I haven't been able to figure it out in SF2 docs.
Possible someone can give me a hint or sample?
Thanks in advance
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
}
}
回答1:
I see in the comments that you already switched to Sf2 forms. I guess you found the RepeatedType
field, which is best for the repeated password field of a registration form - it has a built-in check to verify that the two values match.
Your other problem is checking the uniqueness of an email address. Here's the relevant part of my registration form:
<?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";
}
}
Notes:
$app
is injected so I have access to the dependency injection container$app["user"]
is my User table via KnpRepositoryServiceProvider$app["user"]->findByEmail
returns null or a user record
来源:https://stackoverflow.com/questions/12641897/validating-match-and-unique-using-symfony-validator