Laravel - odebranie błędów walidacji w czystym JS

0

Witam, w jaki sposób mogę odebrać błędy walidacji (Form Request) po wykonaniu żądania AJAX'em w czystym JS? Z tym kodem dostaję w odpowiedzi jedynie HTML obecnej strony.

document.querySelector('form').addEventListener('submit', makeRequest);
 
function makeRequest(e) {
    e.preventDefault();
 
    let username = document.getElementById('username').value;
    let email = document.getElementById('email').value;
    let password = document.getElementById('password').value;
    let password_confirmation = document.getElementById('password_confirmation').value;
    let name = document.getElementById('name').value;
 
    let params = `
        username=${username}
        &email=${email}
        &password=${password}
        &password_confirmation=${password_confirmation}
        &name=${name}
        &_token=${_token}
    `;
 
    let xhr = new XMLHttpRequest();
    xhr.open('POST', registerUrl, true);
    xhr.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');
 
    xhr.onload = function () {
        console.log(this.responseText);
    };
 
    xhr.send(params);
}
0

Przechwyciwszy onerror, będziesz miał dostęp do xhr.status oraz xhr.responseText - w przypadku błędów walidacji, otrzymasz xhr.status === 422 oraz listę błędów w formacie JSON w xhr.responseText.

0

Czy chodzi o coś takiego?

xhr.onerror = function() {
    console.log(this.status);
};

Z tym kodem nie dostaję żadnej odpowiedzi, wina może leżeć po stronie Form Request?

0

Co pokazuje Ci konsola?

0

Z kodem powyżej nie dostaję nic, z takim kodem

xhr.onload = function() {
    console.log(this.responseText);
};

dostaję cały kod html, walidacja raczej dział poprawnie, bo umieszczona w layoucie lista błędów pojawia się w kodzie.
Tu jest Form Request:

<?php

namespace App\Http\Requests;

use Illuminate\Foundation\Http\FormRequest;
use Illuminate\Validation\Rule;

use Illuminate\Validation\Factory;

class RegisterUser extends FormRequest
{
    public function __construct(Factory $factory)
    {
        $factory->extend(
            'has_digit',
            function ($attribute, $value, $parameters) {
                return preg_match('/[\d]+/', $value);
            },
            'The :attribute must contain at least one digit.'
        );

        $factory->extend(
            'has_capital_letter',
            function ($attribute, $value, $parameters) {
                return preg_match('/[A-Z]+/', $value);
            },
            'The :attribute must contain at least one capital letter.'
        );
    }

    /**
     * Determine if the user is authorized to make this request.
     *
     * @return bool
     */
    public function authorize()
    {
        return true;
    }

    /**
     * Get the validation rules that apply to the request.
     *
     * @return array
     */
    public function rules()
    {
        return [
            'username' => 'required|max:30',
            'email' => 'required|email',
            'password' => 'required|min:8|max:20|has_digit|has_capital_letter',
            'password_confirmation' => 'required|same:password'
        ];
    }

    public function messages()
    {
        return [
            'username.required' => '123',
            'username.max' => 'Nazwa użytkownika nie może mieć więcej niż 30 znaków.',
            'email.required' => 'Email jest wymagany.',
            'email.email' => 'Email musi być poprawny.',
            'password.required' => 'Hasło jest wymagane.',
            'password.min' => 'Hasło musi mieć co najmniej 8 znaków.',
            'password.max' => 'Hasło nie może mieć więcej niż 20 znaków.',
            'password.has_digit' => 'Hasło musi mieć co najmniej jedną cyfrę.',
            'password_has_capital_letter' => 'Hasło musi mieć co najmniej jedną wielką literę.',
            'password_confirmation.required' => 'Potwierdzenie hasła jest wymagane.',
            'password_confirmation_same' => 'Hasła muszą się zgadzać.'
        ];
    }
}

Taki kod jQuery działa u mnie poprawnie:

$(function () {

    var form = $('form');

    form.submit(function(e) {

        e.preventDefault();
        $.ajax({
            url     : form.attr('action'),
            type    : form.attr('method'),
            data    : form.serialize(),
            dataType: 'json',
            success : function ( json )
            {
                // Success
                // Do something like redirect them to the dashboard...
            },
            error: function( json )
            {
                if(json.status === 422) {
                    var errors = json.responseJSON;
                    console.log(json.responseJSON);
                } else {
                    // Error
                    // Incorrect credentials
                    // alert('Incorrect credentials. Please try again.')
                }
            }
        });
    });
});

1 użytkowników online, w tym zalogowanych: 0, gości: 1