Validation errors in AJAX mode

前端 未结 8 853
盖世英雄少女心
盖世英雄少女心 2021-01-30 00:14

Currently I use this to display validation errors via ajax:

            if (data.validation_failed == 1)
            {
                var arr = data.errors;
            


        
8条回答
  •  离开以前
    2021-01-30 00:46

    Laravel 5 returns validation error automatically

    for that you just need to do following thing,

    Controller:

    public function methodName(Request $request)
    {
        $this->validate($request,[
            'field-to-validate' => 'required'
        ]);
    
        // if it's correctly validated then do the stuff here
    
        return new JsonResponse(['data'=>$youCanPassAnything],200);
    }
    

    View:

             $.ajax({
                type: 'POST',
                url: 'url-to-call',
                data: {
                    "_token": "{{ csrf_token() }}",
                    "field": $('#field').cal()
                },
                success: function (data) {
                    console.log(data);
                },
                error: function (reject) {
                    if( reject.status === 422 ) {
                        var errors = $.parseJSON(reject.responseText);
                        $.each(errors, function (key, val) {
                            $("#" + key + "_error").text(val[0]);
                        });
                    }
                }
            });
    

    you can build for each validation field one tag with id as field name and suffix _error so it will show validation error with above logic like as follow,

    
    

    Hope it helps :)

提交回复
热议问题