Answer the question
In order to leave comments, you need to log in
How to get validator errors in json?
How to get validator errors in json (Laravel, Ajax) ?
I tried this, but I get an error (code 500)
Fetch request
let data2 ;
let datasend ;
input_login.onblur = async () => {
if(input_login.value != "") {
let checkLogin = input_login.value;
let _token = $("input[name='_token']").val();
let response = await fetch("/email-exist", {
method: 'POST',
headers:{"Content-Type":'application/json'},
body:JSON.stringify({
"_token":_token,
"checkLogin":checkLogin
})
})
datasend = await response.json();
console.log(datasend)
}}
Route::post('/email-exist', '[email protected]');
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use Illuminate\Validation\ValidationException;
use Illuminate\Support\Facades\Validator;
class ExistEmailController extends Controller
{
public function CheckingLogin(Request $req) {
$rules = [
'checkLogin' => 'required|min:5|max:50'
];
$validatedData = Validator::make($req->checkLogin, $rules);
if($validatedData->fails()) {
return response()->json($validatedData->messages(), 200);
}
}
}
Answer the question
In order to leave comments, you need to log in
https://laravel.com/docs/7.x/validation#form-reque... Pay
attention to exception handling, if it exists, this option may not work:
public function authorize(): bool
{
return true;
}
public function rules(): array
{
return [
'post' => 'required|numeric|exists:blog_posts,id',
'content' => 'required|min:2',
];
}
public function messages(): array
{
return [
'post.required' => 'Ошибка идентификации поста',
'post.exists' => 'Ошибка идентификации поста',
'post.numeric' => 'Ошибка идентификации поста',
'content.required' => 'Текст комментария не может быть пустым',
'content.min' => 'Слишком короткий комментарий',
];
}
public function failedValidation(Validator $validator): void
{
$response = [];
$errors = (new ValidationException($validator))->errors();
foreach ($errors as $element) {
foreach ($element as $message) {
$response[] = $message;
}
}
throw new HttpResponseException(
response()->json($response, JsonResponse::HTTP_UNPROCESSABLE_ENTITY)
);
}
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question