php - 如何在 Laravel 5.5 中获取验证消息

标签 php laravel validation laravel-validation laravel-5.5

大家好,我正在 Laravel 5.5 上工作,我需要为我的 API 显示验证消息,到目前为止我已经这样做了

$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 有一些很棒的验证功能,我希望像这样验证我的请求

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

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

所做的那样

最佳答案

Laravel 5.5 中,例如 documentation提一下,验证过程非常简单:

  • 显示验证错误:

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.

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 请求和验证:

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 会自行处理这些问题 :)

关于php - 如何在 Laravel 5.5 中获取验证消息,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46487040/

相关文章:

php - 单一登录表单的数据库查询从两个注册表中提取数据

php - 按分解的键字符串对数组进行分组

laravel - 如何在流明中执行 {{ asset ('/css/app.css' ) }} ?

javascript - 如何在 VueJS 中添加显示而不重新渲染整个组件

java - 如何使用不同的类进行玩家输入验证

php - 不同属性的不同 Getter 和 Setter

php - 解析 define() 内容的正则表达式,可能吗?

php - Laravel 5.0 Eloquent 地没有为 created_at 和 updted_at 添加时间戳

c++ - 是否可以在 C++ 的 Mutator 中使用 Mutator?

c# - 使用 Regex 的 DataValidation 不起作用