$app->post('/', function () use ($app) {
$email = new Input('email');
$email->getValidatorChain()
->addValidator(new Validator\EmailAddress());
$password = new Input('name');
$password->getValidatorChain()
->addValidator(new Validator\StringLength(1));
$inputFilter = new InputFilter();
$inputFilter->add($email)
->add($password)
->setData($_POST);
if ($inputFilter->isValid()) {
// do stuff
$app->redirect('/');
} else {
$field_errors = array();
foreach ($inputFilter->getInvalidInput() as $field => $error) {
foreach ($error->getMessages() as $message) {
$field_errors[] = str_replace('Value', ucfirst($field), $message);
}
}
$app->render('index.php', array('field_errors' => $field_errors));
}
});
我目前使用Slim Framework并使用Zend InputFilter获得上述代码。但是,我想检索错误消息。我不断获得“价值......”所以我对它们str_replace
进行了Email is not a valid email
,如下所示:
$field_errors = array();
foreach ($inputFilter->getInvalidInput() as $field => $error) {
foreach ($error->getMessages() as $message) {
$field_errors[] = str_replace('Value', ucfirst($field), $message);
}
}
这是从Zend InputFilter获取错误消息的正确方法还是还有其他什么?
答案 0 :(得分:5)
你只需要调用$ inputFilter-> getMessages()来获取一个键控数组:
array(
'input' -> 'message',
'inputtwo' => 'anothermessage',
);
这在内部使用了getInvalidInput(),所以不需要那些嵌套的foreach循环,对getMessages()的单个调用应该没问题。