如何在 Symfony 的控制器中验证电子邮件地址 3.x

How to validate an email address in a Controller in Symfony 3.x

我在我的 Symfony 项目中集成了 FOSUserBundle 和 HWIOAUTHBundle。我在 FOSUserBundle 的简单登录表单旁边有一个 facebook 和一个 google login/registration。但是,Facebook 不一定会给我回复电子邮件,因为 Facebook 帐户不需要它(即当用户通过 phone 在 Facebook 上注册时)。在这种情况下,当用户注册时,我将 her/his 电子邮件地址设置为与 facebook/google ID 相同(因为我不能将电子邮件字段留空)。

当有人在我的网站上订购商品时,我需要向他发送一封包含 QR 码的电子邮件,she/he 将使用该二维码来验证自己的身份,因此我需要一种获取真实电子邮件地址的方法来自用户。

我认为当用户通过 Facebook 注册并尝试购买产品时,我会将 her/him 重定向到个人资料编辑页面,显示 he/she 应该提供正确电子邮件的通知地址,然后 she/he 可以继续购买。

但是,我需要在处理购买的控制器中验证他们当前的电子邮件地址是否真实(或至少看起来真实)。

我如何在控制器中使用 Symfony 的验证器来检查来自 $user = $this->get('security.token_storage')->getToken()->getUser(); $user->getEmail(); 的用户电子邮件是否真的看起来像一封电子邮件?

现在这是我拥有的:

if (!$this->get('security.authorization_checker')->isGranted('IS_AUTHENTICATED_FULLY')) {
    throw $this->createAccessDeniedException('some message');
}

$user = $this->get('security.token_storage')->getToken()->getUser();

if ($user->isEnabled() == false) {
    throw $this->createAccessDeniedException('some message');
}

if (null == $user->getEmail() || $user->getFacebookId() == $user->getEmail() || $user->getGoogleId() === $user->getEmail()) {
    $session = new Session();
    $session->getFlashBag()->add('warning', 'Please provide a real email address, yata yata, etc.');
    return $this->redirectToRoute('fos_user_profile_edit');
}

提前致谢!

您应该能够只使用 validator 服务并为其提供值和约束(或组合约束列表)

这个简单的示例应该可以工作(对于 sf 3.3+,取决于您的服务定义策略,您可能必须通过构造函数注入它)

public function testAction()
{
    $constraint = new \Symfony\Component\Validator\Constraints\Email();
    $stringToTest = 'lorem@ipsum.com';

    $errors = $this->get('validator')->validate($stringToTest, $constraint);

    if(count($errors) > 0) {
        //no valid email
    }
}

在你的控制器中试试这个

    ...
use Symfony\Component\Validator\Validator\ValidatorInterface;

// ...
public function addEmailAction($email, ValidatorInterface $validator)
{
    $emailConstraint = new Assert\Email();
    // all constraint "options" can be set this way
    $emailConstraint->message = 'Invalid email address';

    // use the validator to validate the value
    $errorList = $validator->validate(
        $email,
        $emailConstraint
    );

在此处查看文档 https://symfony.com/doc/current/validation/raw_values.html