如何从Respect \ Validation获取验证错误消息?

时间:2012-11-16 13:31:39

标签: php validation respect-validation

我一直在使用Respect Validation进行表单验证

$app->post('/', function () use ($app) {

    $validator  = v::key('name', v::string()->notEmpty())
                    ->key('email', v::email()->notEmpty())
                    ->key('message', v::string()->notEmpty());

    $errors = array();

    try{
        $validator->assert($_POST);
    } catch (\InvalidArgumentException $e) {
        $errors = $e->findMessages(array(
            'notEmpty'     => '{{name}} is required',
            'email'        => '{{name}} must be a valid email'
        ));
    }

    if ($validator->validate($_POST)) {
        // do stuff

        $app->redirect('/');

    } else {

        $app->render('index.php', array('field_errors' => array_values($errors)));

    }
});

循环array_values($errors)会给我:

"" is required
email must be a valid email

我需要类似的东西:

name is required
email must be a valid email
message is required

如何使用Respect Validation

完成

2 个答案:

答案 0 :(得分:4)

消息已存在,但您的findMessages查询正在搜索notEmptyemail

$errors中您实际拥有的是:

Array
(
    [0] => 
    [1] => email must be a valid email
)

$errors[0]是您查找未找到的notEmpty $errors[1]是您找到的email的查找。

如果您更改它以查找有问题的字段nameemailmessage

    $errors = $e->findMessages(array(
        'name'         => '{{name}} is required',
        'email'        => '{{name}} must be a valid email',
        'message'      => '{{name}} is required'
    ));

然后您将获得所需的结果:

Array
(
    [0] => name is required
    [1] => email must be a valid email
    [2] => message is required
)

原谅延迟回复我纯粹偶然发现了这个错误,如果请求官方Respect\Validation issue tracker提供支持,你会发现更快的结果。这也是您可能提出的任何改进建议的理想平台,以帮助您避免遇到的问题。你会发现Respect团队渴望,友好并乐于助人。

的nJoy!

答案 1 :(得分:0)

我认为上面的答案是关闭的。您只需添加一个错误消息代码块,其中包含消息以及名称和电子邮件。

 $errors = $e->findMessages(array(
    'notEmpty'     => '{{name}} is required',
    'email'        => '{{email}} must be a valid email',
    'notEmpty'     => '{{message}} please enter a message'
));