如何在 Laravel 验证中添加错误消息?

How I can add error message in Laravel validate?

请帮忙。 “如何在 laravel 中添加错误用户错误”我想显示 JSON 文件 - 错误 $regex - 规则 我需要在不正确的 sourceUrl

上出错
           $this->validate($request,[
            'title' => 'required|min:10|max:250', //work
            'subTitle' =>'sometimes|present|nullable|min:10|max:250', //work
            'message' => 'required|min:10',//work
            'recommendPic' => 'present|nullable', //work
            'pic' => 'required|sometimes', //file - check upload file,image need fix
            'sourceUrl' =>'required|regex:'.$regex,
       ],[
            'sourceUrl.regex:'.$regex=>'mistake',
       ]);

'sourceUrl.regex:'.$regex=>'mistake', 无效 PHP 代码。

应该是这样的:'sourceUrl.regex' => 'regex mistake'

这将重定向回错误消息 regex mistake

在您看来,您可以使用 @error('sourceUrl') {{ $message }}@enderror 打印消息。

您需要 return 您的验证失败消息,类似于以下内容:

$validation = Validator::make($request->all(), [
    'title' => 'required|min:10|max:250', //work
    'subTitle' =>'sometimes|present|nullable|min:10|max:250', //work
    'message' => 'required|min:10',//work
    'recommendPic' => 'present|nullable', //work
    'pic' => 'required|sometimes', //file - check upload file,image need fix
    'sourceUrl' =>'required|regex:'.$regex,
]);

// if validation fails
if ($validation->fails()) {
  return response()->json([
    'status' => 'failure',
    'errors' => $validation->errors()
  ], 400);
}

// validation passes
return response()->json(['status' => 'success'], 200);