2013-08-19 32 views

回答

42

通過使用Validator服務的validateValue方法

use Symfony\Component\Validator\Constraints\Email as EmailConstraint; 
// ... 

public function customAction() 
{ 
    $email = 'value_to_validate'; 
    // ... 

    $emailConstraint = new EmailConstraint(); 
    $emailConstraint->message = 'Your customized error message'; 

    $errors = $this->get('validator')->validateValue(
     $email, 
     $emailConstraint 
    ); 

    // $errors is then empty if your email address is valid 
    // it contains validation error message in case your email address is not valid 
    // ... 
} 
// ... 
+0

的Merci艾哈邁德.... –

+12

請注意,自Symfony 2.5開始不推薦使用validateValue,而應使用驗證。 –

+2

Validator服務自2.5版開始不推薦使用,將在3.0中刪除。應使用Validator \ RecursiveValidator –

10

如果要創建在控制器本身的形式,並且要驗證電子郵件的動作,那麼代碼如下所示。

// add this above your class 
use Symfony\Component\Validator\Constraints\Email; 

public function saveAction(Request $request) 
{ 
    $form = $this->createFormBuilder() 
     ->add('email', 'email') 
     ->add('siteUrl', 'url') 
     ->getForm(); 

    if ('POST' == $request->getMethod()) { 
     $form->bindRequest($request); 

     // the data is an *array* containing email and siteUrl 
     $data = $form->getData(); 

     // do something with the data 
     $email = $data['email']; 

     $emailConstraint = new Email(); 
     $emailConstraint->message = 'Invalid email address'; 

     $errorList = $this->get('validator')->validateValue($email, $emailConstraint); 
     if (count($errorList) == 0) { 
      $data = array('success' => true); 
     } else { 
      $data = array('success' => false, 'error' => $errorList[0]->getMessage()); 
     } 
    } 

    return $this->render('AcmeDemoBundle:Default:update.html.twig', array(
     'form' => $form->createView() 
    )); 
} 

我也是新的,學習它,任何建議將不勝感激...

+0

非常感謝Amit ... –

+0

Bienvenue Milos –

14

我寫的各種形式的戶外驗證電子郵件地址(ES)(一個或多個)後

http://konradpodgorski.com/blog/2013/10/29/how-to-validate-emails-outside-of-form-with-symfony-validator-component/

它還覆蓋了您驗證對電子郵件約束,而忘記了NotBlank

/** 
* Validates a single email address (or an array of email addresses) 
* 
* @param array|string $emails 
* 
* @return array 
*/ 
public function validateEmails($emails){ 

    $errors = array(); 
    $emails = is_array($emails) ? $emails : array($emails); 

    $validator = $this->container->get('validator'); 

    $constraints = array(
     new \Symfony\Component\Validator\Constraints\Email(), 
     new \Symfony\Component\Validator\Constraints\NotBlank() 
    ); 

    foreach ($emails as $email) { 

     $error = $validator->validateValue($email, $constraints); 

     if (count($error) > 0) { 
      $errors[] = $error; 
     } 
    } 

    return $errors; 
} 
常見錯誤

我希望這有助於

+1

Validator服務從版本2.5開始被棄用,在3.0中被刪除。應該使用Validator \ RecursiveValidator來代替 –

4

爲什麼沒有人提到你可以使用'約束'鍵在FormBuilder實例中驗證它?首先,閱讀文檔Using a Form without a Class

'constraints' =>[ 
    new Assert\Email([ 
     'message'=>'This is not the corect email format' 
    ]), 
    new Assert\NotBlank([ 
     'message' => 'This field can not be blank' 
    ]) 
], 

做工精細用symfony 3.1

例子:

namespace SomeBundle\Controller; 

use Symfony\Component\HttpFoundation\Request; 
use Symfony\Component\Form\Extension\Core\Type; 
use Symfony\Component\Validator\Constraints as Assert; 

class DefaultController extends Controller 
{ 

    /** 
    * @Route("kontakt", name="_kontakt") 
    */ 
    public function userKontaktAction(Request $request) // access for all 
    { 

     $default = array('message' => 'Default input value'); 
     $form = $this->createFormBuilder($default) 
     ->add('name', Type\TextType::class,[ 
      'label' => 'Nazwa firmy', 
     ]) 
     ->add('email', Type\EmailType::class,[ 
      'label' => 'Email', 
      'constraints' =>[ 
       new Assert\Email([ 
        'message'=>'This is not the corect email format' 
       ]), 
       new Assert\NotBlank([ 
        'message' => 'This field can not be blank' 
       ]) 
      ], 
     ]) 
     ->add('phone', Type\TextType::class,[ 
      'label' => 'Telefon', 
     ]) 
     ->add('message', Type\TextareaType::class,[ 
      'label' => 'Wiadomość', 
      'attr' => [ 
       'placeholder' => 'Napisz do nas ... ' 
      ], 
     ]) 
     ->add('send', Type\SubmitType::class,[ 
      'label' => 'Wyślij', 
     ]) 
     ->getForm(); 

     $form->handleRequest($request); 

     if ($form->isValid()) { 
      // data is an array with "name", "email", and "message" keys 
      $data = $form->getData(); 
      // send email 
      // redirect to prevent resubmision 
      var_dump($data); 
     } 

     return $this->render('SomeBundle:Default:userKontakt.html.twig', [ 
      'form' => $form->createView() 
     ]); 
    } 

} 

結果: enter image description here

查看關於可用VA的文件建立蓋住類型。 http://api.symfony.com/3.1/Symfony/Component/Validator/Constraints.html

如果要檢查什麼比消息其它可用密鑰,去文檔:

http://symfony.com/doc/current/reference/constraints/Email.html

或導航到:

YourProject \供應商\ symfony的\ symfony \ src \ Symfony \ Component \ Validator \ Constraints \ Email.php

從那裏,你將能夠看到還有什麼可用。

public $message = 'This value is not a valid email address.'; 

public $checkMX = false; 

public $checkHost = false; 

public $strict; " 

另外請注意,我創建和驗證控制器這是不是最好的做法,應該只用於表單,你將永遠不會再使用其他地方在你的應用程序中的形式。

最佳做法是在YourBundle/Form下的分離目錄中創建表單。將所有代碼移到新的ContactType.php類中。 (不要忘記導入FormBuilder類存在,因爲它不會延長你的控制器,將不必通過「$這種」上網本類)

[ContactType類中:]

namespace AdminBundle\Form; 

use Symfony\Component\Form\AbstractType; 
use Symfony\Component\Form\FormBuilderInterface; 
use Symfony\Component\Form\Extension\Core\Type; 
use Symfony\Component\Validator\Constraints as Assert; 

[內控制器:]

use YourBundle/Form/ContactType; 
// use ... 

//... 
$presetData = []; //... preset form data here if you want to 
$this->createForm('AdminBundle\Form\FormContactType', $presetData) // instead of 'createFormBuilder' 
->getForm(); 
// render view and pass it to twig templet... 
// or send the email/save data to database and redirect the form 
+1

謝謝,對於檢查MX&Host,我添加了:new Assert \ Email(['checkHost'=> true,'checkMX'=> true]) – B2GraphiX

0

我爲symfony1.2 3解決方案是以下幾點:

use Symfony\Component\Validator\Constraints\Email as EmailConstraint; 

$email = '[email protected]'; 
// ... in the action then call 
$emailConstraint = new EmailConstraint(); 

$errors = $this->get('validator')->validate(
    $email, 
    $emailConstraint 
); 

$mailInvalid = count($errors) > 0; 
相關問題