Zend EmailAddress Validation returning multiple errors

前端 未结 4 1152
悲&欢浪女
悲&欢浪女 2021-01-15 10:36

I am unable to make Zend_Validate_EmailAddress show only 1 error message when the user enter invalid email address. The code is

$email = new Zend_Form_Elemen         


        
4条回答
  •  执念已碎
    2021-01-15 10:51

    To me, the problem is not that the messages are overly technical for the average user: that's really a side issue that can be handled by overriding the individual message templates.

    For me, the fundamental issue is that this validator inherently returns multiple messages and we only want a single message.

    I have always had to resort to sub-classing the standard validator:

    class PapayaSoft_Validate_EmailAddress extends Zend_Validate_EmailAddress
    {
        protected $singleErrorMessage = "Email address is invalid";
    
        public function isValid($value)
        {
            $valid = parent::isValid($value);
            if (!$valid) {
                $this->_messages = array($this->getSingleErrorMessage());
            }
            return $valid;
        }
    
        public function getSingleErrorMessage()
        {
            return $this->singleErrorMessage;
        }
    
        public function setSingleErrorMessage($singleErrorMessage)
        {
            $this->singleErrorMessage = $singleErrorMessage;
            return $this;
        }
    }
    

    Then usage is as follows:

    $validator = new PapayaSoft_Validate_Email();
    $validator->setSingleErrorMessage('Your email is goofy');
    $element->addValidator($validator, true);
    

    Alternatively, using the short form, you need to add a new namespace prefix for validators so that the short key "EmailAddress" gets picked up from the new non-Zend namespace. Then:

    $element->addValidator('EmailAddress', true, array(
        'singleErrorMessage' => 'Your email is goofy',
    ));
    

    Note: While the question noted by @emaillenin is similar, the accepted answer there does not actually fulfill your requirements. It does set a single error message for the field, but it sounds like you need to have separate messages coming from the two validators (one for email-format, the other for email-already-exists). For that, it seems to me that you need to change the behavior of the EmailAddress validator itself.

提交回复
热议问题