Symfony2 - How to validate an email address in a controller

后端 未结 6 1553
走了就别回头了
走了就别回头了 2021-02-01 18:38

There is an email validator in symfony that can be used in a form: http://symfony.com/doc/current/reference/constraints/Email.html

My question is: How can I use this val

6条回答
  •  误落风尘
    2021-02-01 19:21

    By using validateValue method of the Validator service

    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
        // ...
    }
    // ...
    

提交回复
热议问题