views:

456

answers:

5

This is my code

$firstname = new Zend_Form_Element_Text('firstname', array('id' => 'firstname'));
$firstname->setLabel('Firstname')
     ->addError('Your firstname.')
     ->addFilter('StringTrim')
     ->addFilter('StripTags')
     ->addValidator('StringLength', false, array(1))
     ->setRequired(true);
$form->addElement($firstname);

The addValidator is firing immediately once the page is loaded, showing the error message.

A: 

I can't test right now, but I believe you should be using addErrorMessage() instead of addError(). See the manual and the API docs.

addError() marks the element as invalid as well as set an error message, while addErrorMessage() sets the message that should be used in case the element turns out to be invalid.

mercator
A: 

Even if I use addErrorMessage() the addValidator is firing immediately.

A: 

What version of Zend Framework are you using?
Do you call anywhere in the code $form->isValid()

michal kralik
A: 

You should specify the message when adding the validator (via the messages key in config array). Both addError($yourErrorString) and addErrorMessage($messageIdentifier) will mark the element invalid. Check manual about translating messages from validators...

Tomáš Fejfar
A: 

I think rather than addError() on the form element (which does exactly what you asked it to do) you want to be setting the "messages" parameter to your validator.

Not sure if you can do that at "construction" but something like:

$firstname->getValidator('StringLength')->setMessages(array( 
  'stringLengthTooShort' => '%value% whatever message'
));

Plus - you seem to be testing if the string is empty by testing it at least 1 character long. You might want to switch to "NotEmpty" - pretty sure this will work:

$firstname->addValidator('NotEmpty',true, array('messages'=>'Please Provide your First Name'));
gnarf