One of the most powerful components of Zend Framework is Zend Form. In this article, I will show you how to put an error class on your form field when using Zend Form. This enables you to create a css class to style the form field in the instance of an error.
Extend Zend Form class:
Here we create a form class that extends Zend_Form. We override the isValid() method. We loop through the form->elements and add a class of “error” if the hasErrors() method returns true. We also do a check to see if a class attribute already exists using the getAttrib() method and if so we append the “error” class using a space to separate.
class MyForm extends Zend_Form { public function isValid($data) { $valid = parent::isValid($data); foreach ($this->getElements() as $element) { if ($element->hasErrors()) { $oldClass = $element->getAttrib('class'); if (!empty($oldClass)) { $element->setAttrib('class', $oldClass . ' error'); } else { $element->setAttrib('class', 'error'); } } } return $valid; } }
Now, when you call the isValid method, it will automatically add a class of error to any fields that do not pass validation.
Here’s an example of a form field with the error class after a validation attempt:

Error Form Field Example
Thank you for this tip!
Hi,
It’s works fine on forms but I can’t use this method on subforms any idea?
Yeah – this will work on any Zend_Form type class. My example above only shows you how to implement it on the main form, but there’s no reason why you can’t implement this into a subform.