Zend Framework: How do I set a custom validator on a form element?
Asked Answered
A

1

3

I'm writing a custom validator that checks that at least one field has a value. I want to validate that either 'namefield' or 'idfield' has a value. One of them can be empty, or both can have a value, but at least one of them must have a value.

$nameField = new Zend_Form_Element_Hidden('namefield');
$nameField->setValue($this->nameFieldValue)
          ->addValidator('AtLeastOneHasValue', false, array('idfield'));

From what I understand, my validator will not validate unless I set my form element to required.

->setRequired(true)

But if I set it to required, it automatically validates that it is not empty, and the error message says that it is empty. I want to allow the field to be empty, and validate multiple fields with my custom validator. How do I validate a form element with my custom validator, without setting the form element to required?

Academician answered 23/12, 2008 at 0:36 Comment(0)
N
6

Check this documentation page for the setAllowEmpty() method. This should help you get where you are trying to go.

setAllowEmpty($flag) and getAllowEmpty() allow you to modify the behaviour of optional elements (i.e., elements where the required flag is false). When the 'allow empty' flag is true, empty values will not be passed to the validator chain.

Nadda answered 23/12, 2008 at 0:41 Comment(1)
->setAllowEmpty(false) This was just what I needed. Thanks!Academician

© 2022 - 2024 — McMap. All rights reserved.