Zend Framework Custom Validation Class Error Message

那年仲夏 提交于 2019-12-06 15:05:48

问题


The validation fails as it should but does not return the error message.

       $form->addElement('text', 'phone_number', array(
     'required' => true,
       'validators' => array(
         array('NotEmpty', true, array('messages' => 'Enter a valid Phone Number')),
           array('regex', false, array('pattern' => '/\([0-9]{3}\)\s[0-9]{3}-[0-9]{4}/',
              'messages' => 'Enter a valid Phone Number'
     )),
           'CheckPhoneNumber'),

       ),
   ));

Custom Class:

class Custom_Validators_CheckPhoneNumber extends Zend_Validate_Abstract{
const IN_USE = 'inUse';

protected $_messageTemplates = array(
    self::IN_USE => "'%value%' is currently in use"
);

public function isValid($value)
{
    $this->_setValue($value);

        $user_check = Users::getActive(preg_replace("/[^0-9]/", "", $value));
        if($user_check->id){
            $this->_error(self::IN_USE);
            return false;
        }

  return true;
}

}

Just fails does not give the "IN_USE" error.


回答1:


Is it only the phone_number element which doesn't display errors or are there others?

Have you turned off default decorators with disableLoadDefaultDecorators?

How about this supplying the custom validator in an array:

$form->addElement(
    'text', 'phone_number', array(
        'required' => true,
        'validators' => array(
            array(
                'NotEmpty', true, array(
                    'messages' => 'Enter a valid Phone Number'
                )
            ),
            array(
                'regex', false, array(
                    'pattern' => '/\([0-9]{3}\)\s[0-9]{3}-[0-9]{4}/',
                    'messages' => 'Enter a valid Phone Number'
                )
            ),
            array(
                'CheckPhoneNumber'
            )
        )
    )
);



回答2:


Are you sure that it fails in your custom validator? Try to make sure that it actually fails in the custom validator.

If not, check if you have correct prefix path configured for elements of the form

$form->addElementPrefixPath(
  'Custom_Validators',
  'Custom/Validators',
  'validate'
);

The code for custom validator seems to be fine.




回答3:


   $form->addElement('text', 'phone_number', array(
 'required' => true,
   'validators' => array(
     array('NotEmpty', true, array('messages' => 'Enter a valid Phone Number')),
       array('regex', false, array('pattern' => '/\([0-9]{3}\)\s[0-9]{3}-[0-9]{4}/',
          'messages'=>array(Zend_Validate_Regex::NOT_MATCH=>'%value% is not a valid phone')
 )),
       'CheckPhoneNumber'),

   ),
));


来源:https://stackoverflow.com/questions/2739508/zend-framework-custom-validation-class-error-message

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!