Sjwdavies
Sjwdavies

Reputation: 4173

Zend Framework: Form Validation - Please Fill In 'A' or 'B'

I'm writing an application with Zend Framework. I have a simple form that has two text boxes.

How do I add validation to the form so that at least one of the input boxes should be populated?

Upvotes: 1

Views: 708

Answers (2)

David Weinraub
David Weinraub

Reputation: 14184

You could create a custom validator, something like:

class My_Validate_AtLeastOneNotEmpty implements Zend_Validate_Interface
{    
    protected $thisField;
    protected $otherField;

    protected $messages = array();

    public function __construct($thisField, $otherField){
        $this->thisField = $thisField;
        $this->otherField = $otherField;
    }

    public function isValid($value, $context = null)
    {
        $validator = new Zend_Validate_NotEmpty();
        if (!$validator->isValid($value) && !$validator->isValid($context['otherField'])){
            $this->messages[] = 'At least one of the fields - ' 
                . $thisField . ' or '  . $otherField 
                . ' - must be non-empty';
            return false;
        }
        return true;
    }

    public function getMessages()
    {
        return $this->messages;
    }
}

Then attach this validator to one of the elements, identifying both names:

// create the two fields
$fld1 = new Zend_Form_Element_Text('field1');    
$fld2 = new Zend_Form_Element_Text('field2');

// add the validator to one of them, identifying both fields
$fld1->addValidator(new My_Validate_AtLeastOneNotEmpty('field1', 'field2'));

Typically, we would not need to identify the fieldname of the element to which we are attaching the validator. However, by passing both fieldnames to the validator, we can make the error message a little clearer for the user.

Upvotes: 3

Dirk McQuickly
Dirk McQuickly

Reputation: 2139

Create a radio group with two options, both unchecked. Hide the textfields. With an onclick event on the radio buttons you can show one of the textboxes. Now you can add a required validator to the radio buttons. A little workaround, but the result is the same.

Upvotes: 0

Related Questions