Hi,

I'm running v1.5.1 of the framework and am coming into difficulties with form validation in the Zend_Form class.

The difficulty is that if I have non-required field, the validators attached to the form element still execute.

As an example, take the following form:

$form = new Zend_Form(array(
     'action' => '/form/process',
     'method' => 'post',
     'elements' => array(
         'Fax' => array('text', array(
                'validators' => array(
                              array('stringLength', false, array(8,32)),
                 ),
                 'label' => 'Fax',
          )),

         'submit' => 'submit',
      ),
));

According to the documentation (http://framework.zend.com/manual/en/zend.form.elements.html), unless the property 'required' is set to true, the field defaults to not-required (required:false).

However, when calling $form->isValid($_POST) on the submitted form, if that field is empty (ie, a "" string), the field is still validated and the form's returned as invalid (due to, in this example, the string length being < 8).

Looking at the code in Zend/Form.php, I see in the function isValid(), the following:

    public function isValid(array $data)
    {
        $valid = true;
        foreach ($this->getElements() as $key => $element) {
            if (!isset($data[$key])) {
                if ($element->getRequired()) {
                    $valid = $element->isValid(null, $data) && $valid;
                }
            } else {
                $valid = $element->isValid($data[$key], $data) && $valid;
            }
        }
     .....
     .....

The problem as I see it is that the use of isset() against the $data[$key] is incorrect because isset() will return true even if $data[$key] is an empty string (which is correct behaviour).

As a temporary hack, to get this working, I've changed the call to isset() to strlen(), ie:
    public function isValid(array $data)
    {
        $valid = true;
        foreach ($this->getElements() as $key => $element) {
            if (!strlen($data[$key])) {
                if ($element->getRequired()) {
                    $valid = $element->isValid(null, $data) && $valid;
                }
            } else {
                $valid = $element->isValid($data[$key], $data) && $valid;
            }
        }

And this gets the behaviour which I believe is correct.

A few questions:

1) Is anyone else able to confirm the behaviour I'm reporting?

2) Is the solution to do what I've done, or is there a better idea?

3) Lastly, it's entirely possible that I'm misunderstanding the Zend_Form module in respects of field validation, if so, if you could enlighten me, it would be appreciated.

Thanks in advance for your time,

Jonathan.

Reply via email to