Zend Framework: setting the form field of Zend_Form_Element, how can I change the validator used to ensure that the element is not empty

When using Zend_Form only way to verify that the input is not left blank is to do

 $element->setRequired(true); 

If this is not set, and the element is empty, it seems to me that the check is not performed on the element.

If I use setRequired() , the element automatically gets the standard NotEmpty validator. The fact is that the error message with this validator sucks: "The 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 strange.

Ideally, I would like to be able to use my own class (derived from Zend_Validate_NotEmpty ) to perform non-empty checks.

+4
source share
5 answers

I did it like this (ZF 1.5):

 $name = new Zend_Form_Element_Text('name'); $name->setLabel('Full Name: ') ->setRequired(true) ->addFilter('StripTags') ->addFilter('StringTrim') ->addValidator($MyNotEmpty); 

therefore, addValidator () is the interesting part. The message is installed in the "Errormessage File" file (to link all user messages in one file):

 $MyNotEmpty = new Zend_Validate_NotEmpty(); $MyNotEmpty->setMessage($trans->translate('err.IS_EMPTY'),Zend_Validate_NotEmpty::IS_EMPTY); 

hope this helps ...

+3
source

By default, setRequired (true) tells isValid () to add a NonEmpty check if it does not already exist. Since this check does not exist before calling isValid (), you cannot set this message.

The simplest solution is to simply manually add a NonEmpty check before calling isValid () and set it accordingly.

 $username = new Zend_Form_Element_Text('username'); $username->setRequired(true) ->addValidator('NotEmpty', true, array('messages' => array('isEmpty' => 'Empty!'))); 
+3
source

Add a NotEmpty checker 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 checker does not seem to start unless you also called setRequired () on the element.

In the controller (or anywhere), call $ form-> setTranslator ($ yourTranslator) to localize the error message when printing on the page.

+2
source
+1
source

As far as I can see Changing an error message cannot change a specific error message. Also, in the manual, it looks like it is a function belonging to Zend_Form, but I do not get a method that is not found when using it in an instance of Zend_Form.

And the use case will be really wonderful.

0
source

Source: https://habr.com/ru/post/1276488/


All Articles