duanlidi1051 2012-11-16 13:31
浏览 186

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

I have been using Respect Validation for form 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)));

    }
});

looping through array_values($errors) would give me:

"" is required
email must be a valid email

I need something like:

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

How should it be done using Respect Validation

  • 写回答

2条回答 默认 最新

  • dongwo6477 2013-01-08 17:44
    关注

    The messages are there but your findMessages lookup is searching for notEmpty and email.

    What you actually have in $errors are :

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

    $errors[0] is your lookup for notEmpty which wasn't found.
    $errors[1] is your lookup for email which was found.

    If you change it to look for the fields in question name, email and message:

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

    Then you will get the desired results :

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

    Excuse the delayed response I purely stumbled on this by chance, you will find much quicker results if requesting support from the official Respect\Validation issue tracker instead. This would also be the ideal platform for any suggestions you may have for improvements to help avoid the problems you've experienced. You will find the Respect team eager, friendly and always willing to help.

    nJoy!

    评论

报告相同问题?

悬赏问题

  • ¥15 uniapp uview http 如何实现统一的请求异常信息提示?
  • ¥15 有了解d3和topogram.js库的吗?有偿请教
  • ¥100 任意维数的K均值聚类
  • ¥15 stamps做sbas-insar,时序沉降图怎么画
  • ¥15 买了个传感器,根据商家发的代码和步骤使用但是代码报错了不会改,有没有人可以看看
  • ¥15 关于#Java#的问题,如何解决?
  • ¥15 加热介质是液体,换热器壳侧导热系数和总的导热系数怎么算
  • ¥100 嵌入式系统基于PIC16F882和热敏电阻的数字温度计
  • ¥20 BAPI_PR_CHANGE how to add account assignment information for service line
  • ¥500 火焰左右视图、视差(基于双目相机)