Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Zend Framework: setting a Zend_Form_Element form field to be required, how do I change the validator used to ensure that the element is not blank

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.

like image 875
Robin Barnes Avatar asked Dec 30 '22 11:12

Robin Barnes


2 Answers

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...

like image 189
crono Avatar answered Jan 14 '23 14:01

crono


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!')));
like image 26
Toxygene Avatar answered Jan 14 '23 14:01

Toxygene