有symfony的電子郵件驗證器,可以在表單中使用驗證電子郵件地址:http://symfony.com/doc/current/reference/constraints/Email.htmlSymfony2的 - 如何在一個控制器
我的問題是:我如何使用這個驗證我的controlelr以驗證電子郵件地址?
這可以通過使用PHP preg_match for usere,但我的問題是如果有可能使用已經內置在電子郵件驗證器中的Symfony。
預先感謝您。
有symfony的電子郵件驗證器,可以在表單中使用驗證電子郵件地址:http://symfony.com/doc/current/reference/constraints/Email.htmlSymfony2的 - 如何在一個控制器
我的問題是:我如何使用這個驗證我的controlelr以驗證電子郵件地址?
這可以通過使用PHP preg_match for usere,但我的問題是如果有可能使用已經內置在電子郵件驗證器中的Symfony。
預先感謝您。
通過使用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
// ...
}
// ...
如果要創建在控制器本身的形式,並且要驗證電子郵件的動作,那麼代碼如下所示。
// 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()
));
}
我也是新的,學習它,任何建議將不勝感激...
非常感謝Amit ... –
Bienvenue Milos –
我寫的各種形式的戶外驗證電子郵件地址(ES)(一個或多個)後
它還覆蓋了您驗證對電子郵件約束,而忘記了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;
}
常見錯誤
我希望這有助於
Validator服務從版本2.5開始被棄用,在3.0中被刪除。應該使用Validator \ RecursiveValidator來代替 –
爲什麼沒有人提到你可以使用'約束'鍵在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()
]);
}
}
查看關於可用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
謝謝,對於檢查MX&Host,我添加了:new Assert \ Email(['checkHost'=> true,'checkMX'=> true]) – B2GraphiX
我爲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;
的Merci艾哈邁德.... –
請注意,自Symfony 2.5開始不推薦使用validateValue,而應使用驗證。 –
Validator服務自2.5版開始不推薦使用,將在3.0中刪除。應使用Validator \ RecursiveValidator –