Symfony2 - How to validate an email address in a controller

后端 未结 6 1476
走了就别回头了
走了就别回头了 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条回答
  •  梦毁少年i
    2021-02-01 19:08

    I wrote a post about validating email address(es) (one or many) outside of forms

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

    It also covers a common bug where you validate against Email Constraint and forget about 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;
    }
    

    I hope this helps

提交回复
热议问题