D
D
Dimon3x2019-10-07 13:34:01
Laravel
Dimon3x, 2019-10-07 13:34:01

How to display validation errors with AJAX?

Like this, I pass in the form of an error, without ajax, it works.

public function login(Request $request) {
         $messages = [
            'email.required' => 'Заполните поле',
            'email.email' => 'Вы ввели не email'    
        ];
         
        $validator = Validator::make($request->all(), [
            'email' => 'required|string|email|max:255',
        ], $messages);
        
     if ($validator->fails()) {
          return Redirect::back()->withErrors($validator);
        }
       }

But if you add Ajax, then this method no longer works.
Probably it is necessary to return not by the withErrors method, but somehow differently, how? How to pull out errors in the controller that got into the $validator array? And then return them already
so it gives 500
return response()->json(withErrors($validator));
Here is my solution
$messages = [
            'email.required' => 'Заполните поле',
            'email.email' => 'Вы ввели не email',
            'password.required' => 'Введите пароль',
            'password.min' => 'Пароль слишком короткий (миниум 8 символов)',
        ];
         
        $validator = Validator::make($request->all(), [
            'email' => 'required|string|email|max:255',
            'password' => 'required|min:8',
        ], $messages);
        
     if ($validator->fails()) {
          //return Redirect::back()->withErrors($validator); //без аякса
         return response()->json($validator->errors());
        }

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Alex Wells, 2019-10-07
@Alex_Wells

$validator->validate();
Nothing more needs to be done.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question