从Zend InputFilter检索错误消息

时间:2012-11-16 11:39:51

标签: php zend-form zend-framework2 zend-inputfilter

$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获取错误消息的正确方法还是还有其他什么?

1 个答案:

答案 0 :(得分:5)

你只需要调用$ inputFilter-> getMessages()来获取一个键控数组:

array(
    'input' -> 'message', 
    'inputtwo' => 'anothermessage',
);

这在内部使用了getInvalidInput(),所以不需要那些嵌套的foreach循环,对getMessages()的单个调用应该没问题。