如何在Laravel 5.5中获取验证消息 [英] How to get validation message in laravel 5.5

查看:131
本文介绍了如何在Laravel 5.5中获取验证消息的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在研究Laravel 5.5,在这里,我需要像现在这样显示API的验证消息

hi folks I'm working on Laravel 5.5 and here I need to display validation messages for my API upto now I have done like this

$validator = Validator::make($request->all(),[
            'first_name' => 'email|required',
            'last_name' => 'nullable',
            'email' => 'email|required',
            'mobile_no' => 'nullable|regex:/^[0-9]+$/',
            'password' => 'required',
        ]);
        if($validator->fails)
        {
            $this->setMeta('status', AppConstant::STATUS_FAIL);
            $this->setMeta('message', $validator->messages()->first());
            return response()->json($this->setResponse(), AppConstant::UNPROCESSABLE_REQUEST);
        }

由于Laravel 5.5具有一些很棒的验证功能,我希望以此方式验证我的请求

Since Laravel 5.5 has some awesome validation features I am looking to validate my request like this

request()->validate([
            'first_name' => 'email|required',
            'last_name' => 'nullable',
            'email' => 'email|required',
            'mobile_no' => 'nullable|regex:/^[0-9]+$/',
            'password' => 'required',
        ]);

但是我在这里面临的问题是,我应该怎么做才能检查验证是否失败?就像我在if($validator->fails)

But I am facing issue here what should I do to check if the validation fails? Like I was doing by if($validator->fails)

推荐答案

Laravel 5.5 中,例如

In Laravel 5.5, like the documentation mention, the validation process is very easy :

  • 显示验证错误:

因此,如果传入的请求参数未通过给定的参数该怎么办 验证规则?如前所述,Laravel将自动 将用户重定向到他们以前的位置.此外,所有 验证错误将自动刷新到会话中.

So, what if the incoming request parameters do not pass the given validation rules? As mentioned previously, Laravel will automatically redirect the user back to their previous location. In addition, all of the validation errors will automatically be flashed to the session.

同样,请注意,我们不必显式绑定错误 消息发送到我们的GET路线中的视图.这是因为Laravel会 检查会话数据中的错误,并将其自动绑定到 视图(如果有).

Again, notice that we did not have to explicitly bind the error messages to the view in our GET route. This is because Laravel will check for errors in the session data, and automatically bind them to the view if they are available.

  • AJAX请求和验证:
    • AJAX Requests & Validation :
    • 在此示例中,我们使用传统形式将数据发送到 应用.但是,许多应用程序都使用AJAX请求.使用时 在AJAX请求期间验证方法,Laravel将不会生成 重定向响应.相反,Laravel会生成JSON响应 包含所有验证错误.此JSON响应将是 使用422 HTTP状态代码发送.

      In this example, we used a traditional form to send data to the application. However, many applications use AJAX requests. When using the validate method during an AJAX request, Laravel will not generate a redirect response. Instead, Laravel generates a JSON response containing all of the validation errors. This JSON response will be sent with a 422 HTTP status code.

      因此,您说过:这意味着您不需要花费ifs来处理验证,laravel会很好地照顾他们:)

      这篇关于如何在Laravel 5.5中获取验证消息的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆