kar*_*m79 2 php validation zend-framework
我Zend_Validate用来验证一些表单输入(Zend Framework版本是1.8.2).出于某种原因,使用此处Zend_Filter_Input描述的界面不起作用:
$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
Run Code Online (Sandbox Code Playgroud)
输出来自debug($messages):
Array
(
[driverName] => Array
(
[isEmpty] => You must give a non-empty value for field 'driverName'
)
)
Run Code Online (Sandbox Code Playgroud)
无论我做什么,我都无法覆盖那条消息.如果我直接使用验证器,即:
$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);
}
Run Code Online (Sandbox Code Playgroud)
输出来自debug($messages):
Array
(
[isEmpty] => Please enter your name
)
Run Code Online (Sandbox Code Playgroud)
底线.我可以让验证器工作,但没有Zend_Filter_Input验证接口方法的好处,我也可以编写自己的验证类!
有没有人知道为什么会这样,以及如何解决它?
它可能是一个错误吗?
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.')
),
);
Run Code Online (Sandbox Code Playgroud)
但是,在您的情况下,您收到的错误消息来自allowEmptyZend_Filter_Input 的meta命令.这不是真正的标准验证器.您可以这样设置:
$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);
Run Code Online (Sandbox Code Playgroud)
如果每个字段需要不同的非空消息,我建议设置allowEmpty => true并添加NotEmpty带有自定义消息的验证器.
供您参考,NotEmpty验证器的正确消息密钥是Zend_Validate_NotEmpty::IS_EMPTY
| 归档时间: |
|
| 查看次数: |
2375 次 |
| 最近记录: |