代码之家  ›  专栏  ›  技术社区  ›  karim79

为什么我不能覆盖默认的验证错误消息?

  •  2
  • karim79  · 技术社区  · 15 年前

    我在用 Zend_Validate 验证某些表单输入(Zend框架版本为1.8.2)。出于某种原因,使用 Zend_Filter_Input 接口如前所述 here 不起作用:

    $data = $_POST;
    $filters = array('*' => array('StringTrim'));
    $validators = array('driverName' => array('NotEmpty','messages' => 'This should override the default message but does not!'));
    $inputFilter = new Zend_Filter_Input($filters,$validators,$data);
    $messages = $inputFilter->getMessages();
    debug($messages); //show me the variable contents
    

    输出自 debug($messages) :

    Array
    (
        [driverName] => Array
            (
                [isEmpty] => You must give a non-empty value for field 'driverName'
            )
    
    )
    

    不管我做什么,我都不能忽略这个信息。如果我直接使用验证器,即:

    $notEmpty = new Zend_Validate_NotEmpty();      
    $notEmpty->setMessage('This WILL override the default validation error message');
    if (!$notEmpty->isValid($_POST['driverName'])) {
        $messages = $notEmpty->getMessages();
        debug($messages);
    }
    

    输出自 调试($messages) :

    Array
    (
        [isEmpty] => Please enter your name
    )
    

    底线。我可以让验证器工作,但是没有 Zend_滤波器输入 接口方法的验证我也可以写自己的验证类!

    有人知道为什么会发生这种情况,以及如何解决它吗?

    可能是个虫子吗?

    3 回复  |  直到 15 年前
        1
  •  5
  •   jason    15 年前

    这个 messages 必须向验证程序数组中的键传递一个键/值对数组,其中键是验证消息常量,值是自定义错误消息。下面是一个例子:

        $validators = array(
    
            'excerpt' => array(
                'allowEmpty' => true,
                array('StringLength', 0, Ctrl::getOption('blog/excerpt/length')), 
                'messages' => array(Zend_Validate_StringLength::TOO_LONG => 'The post excerpt must not exceed '.Ctrl::getOption('blog/excerpt/length').' characters.')
            ),
    
        );
    

    但是,在您的情况下,您收到的错误消息来自 allowEmpty zend_filter_输入的元命令。这不是真正的标准验证器。您可以这样设置:

    $options = array(
        'notEmptyMessage' => "A non-empty value is required for field '%field%'"
    );
    
    $input = new Zend_Filter_Input($filters, $validators, $data, $options);
    
    // alternative method:
    
    $input = new Zend_Filter_Input($filters, $validators, $data);
    $input->setOptions($options);
    

    如果每个字段需要不同的非空消息,我建议设置 allowEmpty => true 添加一个 NotEmpty 带有自定义消息的验证程序。

    请参考 诺威蒂 验证器是 Zend_Validate_NotEmpty::IS_EMPTY

        2
  •  1
  •   Steve Goodman    15 年前

    messages参数采用数组,而不是字符串。试试这个:

    $validators = array('driverName' => 
                         array('NotEmpty',
                               'messages' => array(
                                    0 => 'This should override the default message but does not!'
                                )
                         )
                  );
    
        3
  •  0
  •   user155974    15 年前

    这是一个bug,它在Zend框架的jira中…