Reputation: 13541
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.
Upvotes: 4
Views: 8237
Reputation: 453
Add a NotEmpty validator, and add your own message:
// In the form class:
$username = $this->createElement('text', 'username');
$username->setRequired(); // Note that this seems to be required!
$username->addValidator('NotEmpty', true, array(
'messages' => array(
'isEmpty' => 'my localized err msg')));
Note that the NotEmpty validator doesn't seem to be triggered unless you've also called setRequired() on the element.
In the controller (or wherever), call $form->setTranslator($yourTranslator) to localize the error message when it's printed to the page.
Upvotes: 2
Reputation: 487
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!')));
Upvotes: 3
Reputation: 3663
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...
Upvotes: 4
Reputation: 13541
As far as I can see Changing the error message has no way of changing the message of a specific error. Plus the manual makes it look like like this is a function belonging to Zend_Form, but I get method not found when using it on an instance of Zend_Form.
And example of the useage would be really great.
Upvotes: 0