0

Using Symfony1, how could I validate one of two fields is being filled in in a form? They are but not required fields but I need the user to fill in one of the two field. This is my attempt so far, but it doesn't work:

$this->setValidator('phone', new sfValidatorAnd(
  array(
    new sfValidatorSchemaCompare('email', '==', ''),
    new sfValidatorSchemaCompare('phone', '==', ''),
  ),
  array(),
  array(
    'invalid' => 'El e-mail no tiene un formato correcto',
    'required' => 'Campo obligatorio',
  )
));

2 Answers 2

3

When comparing two separate fields you should use a global validator: http://www.symfony-project.org/forms/1_2/en/02-Form-Validation#chapter_02_global_validators. Your current approach will always mark the phone field as invalid when an error occurs. Also, the conditions you supply to the validator should return true when the values are valid so in your case you should be using a ValidatorOr with != comparisons like this:

$this->validatorSchema->setPostValidator(new sfValidatorOr(
  array(
    new sfValidatorSchemaCompare('email', '!=', ''),
    new sfValidatorSchemaCompare('phone', '!=', ''),
  ),
  array(),
  array('invalid' => 'Campo obligatorio')
));

Hope that helps.

Sign up to request clarification or add additional context in comments.

2 Comments

i try it but it never raise an error. not create register but neither show me the error. how can i show the error? thanks.
symfony-project.org/forms/1_2/en/… You can use $form->hasGlobalErrors() to check and echo $form->renderGlobalErrors() to print. If you'd like to do custom rendering you can iterate through $form->getGlobalErrors() for name/message pairs of all global errors as well.
0

I'm not sure if there is a better method but you could use sfValidatorOr to check if one of the fields validates (i.e set required to true).

More about sfValidatorOr: http://www.symfony-project.org/forms/1_2/en/B-Validators#chapter_b_sub_sfvalidatoror

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.