A validator's setMessage("...") may be used to change the error message when
a validator fails. For example:

   $formElement->getValidator('StringLength')->setMessage("Your password
must be at least 6 characters long.");


However, the NotEmpty validator (created automatically when
setRequired(true) has been called on an element) cannot have it's message
changed in the same way. This is because it is added, not at the time of the
setRequired(true) call, but only when validate() is called:


First off, wouldn't it make more sense if the default error message was
"This value may not be left blank." in the first place, rather than, "Value
is empty, but a non-empty value is required"?

But secondly, there should be a consistent method of changing any error
message. The current implementation is inconsistent, because it prevents the
specified API for changing a validator's message from functioning. And that
is because the validator does not exist, until validate() is called on the
element:

----- From Element.php ------ 

    public function isValid($value, $context = null)
    {
        $this->setValue($value);
        $value = $this->getValue();

        if (empty($value) && !$this->isRequired() && $this->getAllowEmpty())
{
            return true;
        }

        if ($this->isRequired() 
            && $this->autoInsertNotEmptyValidator() 
            && !$this->getValidator('NotEmpty'))
        {
            $validators = $this->getValidators();
            $notEmpty   = array('validator' => 'NotEmpty',
'breakChainOnFailure' => true);
            array_unshift($validators, $notEmpty);
            $this->setValidators($validators);
        }
----------------------------------

   One possible fix would be for the ZF team to create the NotEmpty
validator within setRequired. That way, later calls to
getValidator('NotEmpty') will succeed.


I suppose another solution might be to create a Translator. Does a
translator get called even for translations to English?

When writing new code, the simplest fix while we await an update to ZF
1.5.1, is to still use setRequired(true), but explicitly create the NotEmpty
validator beforehand:

        $password = $this->createElement('password', ...
        $password->addValidator('NotEmpty');
        $password->getValidator('NotEmpty')->setMessage("Please enter your
password.");

        $password->addValidator('StringLength', true, array(6))
                 ->setRequired(true)
                 ->addFilter('StringTrim');

        $password->getValidator('StringLength')->setMessage("Your password must 
be
at least 6 characters long.");


-- 
View this message in context: 
http://www.nabble.com/Form-Validator%3A-Empty-Element-Error-Message-Customization-tp17396349p17396349.html
Sent from the Zend Framework mailing list archive at Nabble.com.

Reply via email to