When using a Zend_Form
, the only way to validate that an input is not left blank is to do
$element->setRequired(true);
If this is not set and the element is blank, it appears to me that validation is not run on the element.
If I do use setRequired()
, the element is automatically given the standard NotEmpty validator. The thing is that the error message with this validator sucks, "Value is empty, but a non-empty value is required". I want to change this message. At the moment I have done this by changing the Zend_Validate_NotEmpty
class, but this is a bit hacky.
I would ideally like to be able to use my own class (derived from Zend_Validate_NotEmpty
) to perform the not empty check.
I did it this way (ZF 1.5):
$name = new Zend_Form_Element_Text('name');
$name->setLabel('Full Name: ')
->setRequired(true)
->addFilter('StripTags')
->addFilter('StringTrim')
->addValidator($MyNotEmpty);
so, the addValidator() is the interesting part. The Message is set in an "Errormessage File" (to bundle all custom messages in one file):
$MyNotEmpty = new Zend_Validate_NotEmpty();
$MyNotEmpty->setMessage($trans->translate('err.IS_EMPTY'),Zend_Validate_NotEmpty::IS_EMPTY);
hope this helps...
By default, setRequired(true) tells isValid() to add a NonEmpty validation if one doesn't already exist. Since this validation doesn't exist until isValid() is called, you can't set the message.
The easiest solution is to simply manually add a NonEmpty validation before isValid() is called and set it's message accordingly.
$username = new Zend_Form_Element_Text('username');
$username->setRequired(true)
->addValidator('NotEmpty', true, array('messages' => array('isEmpty' => 'Empty!')));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With