2013-08-19 20 views
16

istnieje validator email w Symfony, które mogą być stosowane w postaci: http://symfony.com/doc/current/reference/constraints/Email.htmlSymfony2 - Jak sprawdzić poprawność adresu e-mail w kontrolerze

Moje pytanie brzmi: W jaki sposób można wykorzystać ten walidator w moim controlelr w celu potwierdzić adres e-mail?

Jest to możliwe przy użyciu PHP preg_match dla usere, ale moje pytanie brzmi, czy istnieje możliwość użycia Symfony wbudowanego już weryfikatora wiadomości e-mail.

Z góry dziękuję.

Odpowiedz

42

Korzystając validateValue metodę usługi Validator

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 Ahmed .... –

+12

Należy zauważyć, że validateValue jest przestarzałe od Symfony 2.5 i zamiast tego należy użyć sprawdzania poprawności. –

+2

Usługa walidatora jest nieaktualna od wersji 2.5, do usunięcia w wersji 3.0. Validator \ RecursiveValidator powinien być użyty zamiast: –

10

Jeśli tworzysz formularz w samym kontrolerze i chcą potwierdzić e-mail w działaniu, wtedy kod będzie wyglądać następująco.

// 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() 
    )); 
} 

Jestem również nowe i uczenie go, wszelkie sugestie będą mile widziane ...

+0

Wielkie dzięki Amit ... –

+0

Bienvenue Milos –

14

napisałem posta o sprawdzanie poprawności adresu e-mail (ES) (jednego lub wielu) poza formami

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

obejmuje ona również wspólny błąd, sprawdzić poprawność przeciwko E Wiązanie i zapomnieć o 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; 
} 

Mam nadzieję, że to pomoże

+1

Usługa walidatora jest nieaktualna od wersji 2.5, do usunięcia w wersji 3.0. Validator \ RecursiveValidator powinien być użyty zamiast: –

4

Dlaczego nikt nie wspomina o tym, że można go sprawdzić w instancji FormBuilder za pomocą klucza "ograniczenia" ?? Przede wszystkim, przeczytaj dokumentację 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' 
    ]) 
], 

Działa dobrze z symfony 3,1

Przykład:

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() 
     ]); 
    } 

} 

Wynik: enter image description here

Zobacz funkcja dokumentowania o dostępnej va typy pokrywek. http://api.symfony.com/3.1/Symfony/Component/Validator/Constraints.html

Jeśli chcesz sprawdzić, jakie są dostępne klucze inne niż wiadomości, przejdź do dokumentacji pod adresem:

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

lub przejdź do:

YourProject \ dostawcy \ symfony \ Symfony \ src \ Symfony \ Komponent \ Walidator \ Ograniczenia \ Email.php

stamtąd będziesz mógł zobaczyć, co jeszcze jest dostępne.

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

public $checkMX = false; 

public $checkHost = false; 

public $strict; " 

Należy również pamiętać, że tworzone i sprawdzane formy wewnątrz sterownika, który nie jest najlepszym rozwiązaniem i powinien być używany tylko do form, które nigdy nie będzie ponownego użycia gdziekolwiek indziej w aplikacji.

Najlepszą praktyką jest tworzenie formularzy w oddzielnym katalogu w ramach YourBundle/Form. Przenieś cały kod do nowej klasy ContactType.php. (Nie zapomnij zaimportować tam klasę FormBuilder gdyż nie przedłuży kontroler i nie będą miały dostępu do tej klasy poprzez „$ to”)

[wewnątrz klasy 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; 

[wewnątrz kontroler:]

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

dzięki za sprawdzenie MX & Host, dodałem: nowy Assert \ Email (['checkHost' => true, 'checkMX' => true]) – B2GraphiX

0

Moje rozwiązanie dla symfony 3 był następujący:

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; 
Powiązane problemy