Zend Framework: Conditional validation
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.');
You can extend the isValid() method in your form class, e.g.
/**
* @param array $data The data from the request to validate
*/
public function isValid($data)
{
$this->checkSpecialityForProfession($data);
return parent::isValid($data)
}
protected function checkSpecialityForProfession($data)
{
if($data['profession'] === 'Dr.') {
$validator = new Zend_Validate_InArray(array(
'Heart',
'Lungs',
'Feet',
'Nose',
)
);
$this->getElement('specialty')->addValidator($validator);
}
}
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();
}
}
This guy figured out a slick way via a custom validation class. http://jeremykendall.net/2008/12/24/conditional-form-validation-with-zend_form/
精彩评论