0

I'm new to zend framework. I created a form where i have 2 text field. Now, i want to validate that one of them is not empty and if so the form is valid. How can i set a validation like this in an InputFilter?

Any help is greatly appreciated.

Wermerb
  • 1,039
  • 3
  • 15
  • 30

1 Answers1

0

To set the validator in an input filter you would do something like this in a validator class:

$inputFilter->add($factory->createInput(array(
    'name'     => 'foo_bar_input',
    'required' => true,
    'filters'  => array(
        array('name' => 'StripTags'),
        array('name' => 'StringTrim')
    ),

    // add your validators here         
    'validators' => array(
        // check to see if an input is empty
        array(
            'name'    => 'Zend\Validator\NotEmpty',
            'options' => array(),
        )
    )
)));

Then to use the filter with your form, do something like:

$validate = $this->getServiceLocator()->get('your_validator_class');
$form->setInputFilter($validate->getInputFilter());

The just check to see if your form is valid:

if ($form->isValid()) 
{ 
    // do stuff
}

Here is ZF2's documentation on the NotEmpty validator: http://framework.zend.com/manual/2.0/en/modules/zend.validator.set.html#notempty

alex
  • 602
  • 4
  • 7
  • Thank you for your answer. I do know this my issue is if there are 2 text input and 1 of them is not allowed to be empty but this is random which one the user fill it out. So how do i validate this situation? – Wermerb May 17 '14 at 21:21
  • So are you saying if they fill out input2 then input1 (the one that couldn't be empty) is no longer required? – alex May 17 '14 at 21:27
  • Then check to see if input2 is empty, if it is, then keep the validator for input1, if input2 has been filled out, then you can disable the validator for input1 since you won't need it. – alex May 17 '14 at 21:33