Laravel Validate Form via Ajax, using the FormRequest class

0

Hello the case is the following, I managed to validate a simple form using the Validator library, now my question is how it would be using a "request" that extends from the class FormRequest . Here I share both the frontend and backend code. Note: I clarify that when validating the data with a request, the function of the JS "success" is executed, but when it does not fulfill the requirements, the function of < strong> JS , "error", and I'm trying to capture the errors to show it in the html , as I'm showing it below.

JS:

    var _url ="{{route('ajax.procesar')}}";
    var _tiempo_espera=20000;
    $(document).ready(inicio);
    function inicio(){
        $("button").click(procesar);
        $.ajaxSetup({
            headers: {
                'X-CSRF-TOKEN': $('meta[name="_token"]').attr('content')
            }
        });
    }

    function procesar(){
        datos = {
            nombre: $("#nombre").val()
            , sexo: $("#sexo").val()
        };
        var div_respuesta="#respuesta";

        $.ajax({
            url: _url,
            type: 'POST',
            data: datos,
            async: true,
            dataType: 'json',
            beforeSend: function () {
                $(div_respuesta).html('Enviando datos');

                $(".alert-danger").html("");
            },
            error: function () {
                alert("Error al enviar los datos");

            },
            success: function (data_response) {

                console.log(data_response);
                $.each(data_response.errors, function(key, value){                        

                    $('#alert-'+key).append('<p>'+value+'</p>');

                });

                if(data_response.success){
                    alert(data_response.success);

                }

            },
            complete: function () {
                $(div_respuesta).html('');
            },
            timeout: _tiempo_espera
        });

    }

The route:

Route::post('/form_ajax', 'AjaxController@procesar')->name('ajax.procesar');

Controller code:

public function procesar(Request $request){

        $validator = Validator::make($request->all(), [
            'nombre' => 'required|min:3',
            'sexo' => 'required|in:M,F'
        ]);

        if ($validator->fails())
        {
            return response()->json(['errors'=>$validator->errors()]);
        }
        return response()->json(['success'=>'Paso!!']);

    }

Now this would be the other way I'm trying to solve.

public function procesar(RequestProcesarAjax $request){
        return response()->json(['success'=>'Paso Con Request!!']);
    }

The RequestProcesarAjax class

<?php

namespace App\Http\Requests;

use Illuminate\Foundation\Http\FormRequest;

class RequestProcesarAjax extends FormRequest
{
    /**
     * 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 [
            'nombre' => 'required|min:3',
            'sexo' => 'required|in:M,F'
        ];
    }
}
    
asked by juan 15.09.2018 в 00:11
source

0 answers