Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Zend validators and error messages: addValidator and addErrorMessage

If I have a form element that has multiple validators attached to it (3 in this example), how would I use addErrorMessage to create custom error messages when each unique validator fails. Is there a way to add a custom message for each validator?

$element = new Zend_Form_Element_Text()...
$element->....
        ->addValidator(...)
        ->addValidator(...)
        ->addValidator(...)
        ->addErrorMessage()
like image 246
jblue Avatar asked Oct 02 '10 07:10

jblue


3 Answers

Typically it's done per validator error message, not per validator...

$element->setErrorMessages(array(Zend_Validate_...::CONSTANT => 'New Message'));

But I often prefer to override all of an element's errors to a single

$element->setErrorMessages(array('Single Error'));

or, if I need it per validator, this works...

$validator->setMessages('string error')

should override all a validator's errors to a single message. I could not find this documented anywhere, but it works for me. Because of this, it may not work for all versions?

To me, the error messaging handling is a bit messy unless you want to override every possible error message, but hopefully one of these solutions works for you.

Cheers

like image 192
Adrian Schneider Avatar answered Nov 12 '22 09:11

Adrian Schneider


Add your message along with the validator as below. Example:

->addValidator('StringLength', false, array(0,255,'messages'=>'Cannot be more than 255 chars'))

->addValidator('NotEmpty', true, array('messages'=>'Cannot be empty'))
like image 40
Jayachandran J Avatar answered Nov 12 '22 08:11

Jayachandran J


Add your message like this

->addValidator( 'Alpha', true, array( 'messages' => array( 'notAlpha' => "Please enter alphabetic character only in Product name.
") ));

Add validator message according to your error string

like image 2
Nilesh Gupta Avatar answered Nov 12 '22 07:11

Nilesh Gupta