简体   繁体   中英

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.

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?

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

Alternatively, as you've mentioned, you can use the sfValidatorEmail class in your action like so:

$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. Symfony forms are lightweight, there's no performance reason to not use them. Instead, make a custom form for this purpose:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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