views:

42

answers:

2

I need to set up some validation for a form field based on a value of another field.

For instance if profession is Doctor, then require specialty not to be blank ('') or none ('none').

$professionOptions = array(
        ''      => 'Choose Profession',
        'Dr.'   => 'Dr.',
        'zzz'   => 'zzz',
        'None'  => 'None');
 $this->validator->field('profession')->inArray(array_keys($professionOptions)) ->message('Invalid profession.');


 $specialtySelectOptions = array(
            ''      => 'Choose Specialty',
            'Heart' => 'Heart',
            'Lungs' => 'Lungs',
            'Feet'  => 'Feet',
            'Nose'  => 'Nose');

How do i make the following dependent on the profession?

$this->validator->field('specialty')->inArray(array_keys($specialtySelectOptions))
                                            ->message('Invalid salutation.');
A: 

I usually go this way

$f = new My_Form();

if($f->isValid($_POST)) {
  // extra validation
  if($f->getValue('profession') === 'Dr.') {
    $specialty = $f->getValue('specialty');
    if($specialty === '' || $specialty === 'none') {
      $f->markAsError();
      $f->specialty->addError('error_msg');
    }
  }

  if(!$f->isErrors()) {
    $f->save();
  }
}
michal kralik
A: 

This guy figured out a slick way via a custom validation class. http://www.jeremykendall.net/2008/12/24/conditional-form-validation-with-zend_form/

txyoji