-1

Help plz. "How add error user mistake in laravel" I want show JSON file - error $regex - reqular rules I need get mistake on not correct 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',
       ]);
Oleg St
  • 9
  • 5
  • Is your issue that you want a custom error message, or that you don't know how to display the error message if your validation fails? – Peppermintology Aug 06 '20 at 07:47
  • yes I dont know how show error message. I want if request sourceUrl not answer on regular rule $regex I get mistake 'mistake'. Now I just get code 201 in postman but dont get message – Oleg St Aug 06 '20 at 07:53
  • I am assuming you're working with an API as you mentioned Postman, if not please clarify in your question. – Peppermintology Aug 06 '20 at 08:08
  • You can do this https://stackoverflow.com/a/62172324/4575350 – STA Aug 06 '20 at 08:22
  • yes API. On this moment problem with show error messages – Oleg St Aug 06 '20 at 08:26

2 Answers2

0

'sourceUrl.regex:'.$regex=>'mistake', is not valid PHP code.

It should be something like: 'sourceUrl.regex' => 'regex mistake'

This redirects back with the error message regex mistake.

In your view you can print the message with @error('sourceUrl') {{ $message }}@enderror.

Ma Kobi
  • 888
  • 6
  • 21
0

You need to return your failed validation messages, something like the following:

$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);
Peppermintology
  • 9,343
  • 3
  • 27
  • 51