简体   繁体   English

如何在Symfony中使用sfValidatorEmail验证器来验证单个电子邮件字段

[英]How can I use the sfValidatorEmail validator in Symfony to validate a single email field

I have a form with 2 elements that will be submitted and then update part of a user profile. 我有一个包含2个元素的表单,将被提交,然后更新用户个人资料的一部分。

I don't want to use the entire generated form and have to remove all the fields except for the two I need. 我不想使用整个生成的表单,并且必须删除除我需要的两个字段以外的所有字段。 I just want to be able to create a quite simple form to do my update. 我只希望能够创建一个非常简单的表单来进行更新。

Is there a way to utilize Symfony's sfValidatorEmail inside the action on the returned value of an email field? 有没有一种方法可以在对电子邮件字段的返回值执行的操作中利用Symfony的sfValidatorEmail?

Since the regex is already written in the validator, I would like to reuse it, but I don't know how to use it in the action after the non-symfony form has been submitted. 由于正则表达式已经在验证器中编写,因此我想重用它,但是在提交非符号形式之后,我不知道如何在操作中使用它。

Two approaches here - you could construct a simple form anyway extending from sfForm / sfFormSymfony (doesn't have to be ORM-based) that just contains the 2 fields you want. 这里有两种方法-无论如何,您都可以构造一个简单的表单,该表单从sfForm / sfFormSymfony (不必基于ORM)扩展,仅包含您想要的2个字段。 That way you can use the existing validation framework, and then use $myForm->getValues() after everything has been validated to get your values for your profile update. 这样,您可以使用现有的验证框架,然后在对所有内容进行验证以获取用于配置文件更新的值之后,使用$myForm->getValues()

Alternatively, as you've mentioned, you can use the sfValidatorEmail class in your action like so: 另外,如前所述,您可以在操作中使用sfValidatorEmail类,如下所示:

$dirtyValue = "broken.email.address"
$v = new sfValidatorEmail();
try
{
  $v->clean($dirtyValue);
}
catch (sfValidatorError $e)
{
  // Validation failed
}

The latter approach quickly leads to messy code if you have many values that need cleaning, and it's worth putting the logic back into a form to handle this in the usual manner. 如果您有许多需要清除的值,则后一种方法会很快导致代码混乱,并且值得将逻辑放回以常规方式处理的形式。

If you're submitting a form with 2 elements, it should be a form on the edit and update end, period. 如果您要提交包含2个元素的表单,则该表单应为编辑和更新结束期间的表单。 Symfony forms are lightweight, there's no performance reason to not use them. Symfony表单是轻量级的,没有性能上的理由不使用它们。 Instead, make a custom form for this purpose: 而是为此目的定制表格:

class ProfileUpdateForm extends ProfileForm
{
  public function configure()
  {
    $this->useFields(array('email', 'other_field'));
  }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM