简体   繁体   English

laravel打印验证错误消息

[英]laravel print the validation error message

I read the official page about validation in laravel http://laravel.com/docs/validation#working-with-error-messages and I followed them. 我在laravel中阅读了有关验证的官方页面,网址为http://laravel.com/docs/validation#working-with-error-messages,然后我跟随了他们。 So my code is 所以我的代码是

 $input = Input::all();
        $validation = Validator::make($input, Restaurant::$rules);

        if ($validation->passes())
        {
            Restaurant::create($input);

            return Redirect::route('users.index');
        }
        else{
            $messages = $validation->messages();
            foreach ($messages->all() as $message)
            {
                echo $message + "</br>";
            }
        }

I can see the error message but it is just 00 . 我可以看到错误消息,但这只是00 Is there a better way to know in which form's field the error is and what is the error description? 有没有更好的方法来知道错误在哪个表单字段中以及错误描述是什么?

I already have rules and I now the input is breaking the rules but I need to read the error message 我已经有了rules ,现在输入违反了规则,但是我需要阅读错误消息

 $messages = $validation->messages();

            foreach ($messages->all('<li>:message</li>') as $message)
            {
                echo $message;
            }

Official Documentation 官方文件

After calling the messages method on a Validator instance, you will receive a MessageBag instance, which has a variety of convenient methods for working with error messages. 在Validator实例上调用messages方法之后,您将收到一个MessageBag实例,该实例具有用于处理错误消息的多种便捷方法。

According to the MessageBag documentation the function all Get all of the messages for every key in the bag. 根据MessageBag文档 ,函数all获取包中每个键的所有消息。

You can access errors through the errors() object, and loop through the all rules' keys. 您可以通过errors()对象访问错误,并遍历所有规则的键。

Something like this: 像这样:

Route::get('error', function(){

    $inputs = array(
        'id'        => 5,
        'parentID'  => 'string',
        'title'     => 'abc',
    );

    $rules = array(
        'id'        => 'required|integer',
        'parentID'  => 'required|integer|min:1',
        'title'     => 'required|min:5',
    );

    $validation = Validator::make($inputs, $rules);

    if($validation->passes()) {
        return 'passed!';
    } else {
        $errors = $validation->errors(); //here's the magic
        $out = '';
        foreach($rules as $key => $value) {
            if($errors->has($key)) { //checks whether that input has an error.
                $out.= '<p>'$key.' field has this error:'.$errors->first($key).'</p>'; //echo out the first error of that input
            }
        }

        return $out;
    }

});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM