2012-09-28 34 views
1

我正在使用Silex進行一個小型項目,但我不確定如何驗證兩個匹配的密碼字段,還要檢查使用數據庫連接的電子郵件的唯一性。我無法在SF2文檔中找到它。驗證匹配和唯一使用Symfony驗證程序

可能有人可以給我一個提示或樣本?

在此先感謝

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

我自己不使用Silex,但是在S2中,唯一的電子郵件有一個UniqueEntity約束(http://symfony.com/doc/current/reference/constraints/UniqueEntity.html),密碼使用重複字段(http ://symfony.com/doc/current/reference/forms/types/repeated.html) – Cerad

+0

切換到使用Symfony形式,因爲它增加了一些功能:)仍然懷疑如何工作的唯一性tho。 – Kristian

回答

5

我看到你已經切換至Sf2形式的評論。我猜你找到RepeatedType這個字段,最好是註冊表單的重複密碼字段 - 它有一個內置檢查來驗證這兩個值是否匹配。

您的其他問題是檢查電子郵件地址的唯一性。通過KnpRepositoryServiceProvider

  • $app["user"]->findByEmail

    • $app注入,所以我有機會獲得依賴注入容器
    • $app["user"]我的用戶表:這是我的登記表的相關部分:

      <?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"; 
          } 
      } 
      

      注意事項返回空或用戶記錄