• This site uses cookies. By continuing to use this site, you are agreeing to our use of cookies. Learn more.

[Solved] Validasi Laravel Dengan Ajax

Kepala Suku

Web & Mobile Developer
Staff member
#1
Kode backend untuk validasi adalah sebagai berikut. Gunakan class validator dan input:
PHP:
use Illuminate\Support\Facades\Validator;
use Illuminate\Support\Facades\Input;
Kode untuk mengubah kesalahan validasi menjadi array:
PHP:
$validator = Validator::make($request->all(), $rules);
        if ($validator->fails())
        {
            $err = $validator->getMessageBag()->toArray();
            foreach ($err as $e => $v){
               $err[] = $v;
            }
            return response()->json(array("err" => $err));
        }
Kode untuk menampilkan error menggunakan Ajax:
JavaScript:
var data = $("#form-add").serialize()
                var btn = $(this)
                btn.button("loading")
                $.ajax({
                    url: "{{url("/companies/create")}}",
                    method: "post",
                    data: data,
                    dataType: 'json',
                    success: function (response) {
                        btn.button("reset")
                        if(response==1){
                            $("#modal-add").modal("hide")
                            $("#form-add").trigger("reset")
                            table.ajax.reload()
                        }else{
                            error(response.err[0])
                            console.log(response.err[0])
                        }
                    },
                    error: function (err) {
                        btn.button("reset")
                        error(err.responseJSON.err[0])
                        console.log(err.responseJSON.err[0])
                    }
                })
 
Last edited:

Kepala Suku

Web & Mobile Developer
Staff member
#2
Variabel rulis dibuat seperti ini:
PHP:
$rules = array(
            'buyer'  => 'required|string|min:3|max:100',
            'ptotal' => 'required|integer|min:1'
        );
 

Kepala Suku

Web & Mobile Developer
Staff member
#3
Laravel 6 Validasi Biasa

PHP:
use Illuminate\Support\Facades\Redirect;
use Illuminate\Support\Facades\Validator;
PHP:
$rules = array(
            'term' => 'required|string|min:1|max:100',
            'desc' => 'required|string|min:20',
        );
        $term = $request->term;
        $validator = Validator::make($request->post(), $rules);
        if ($validator->fails()) {
            $messages = $validator->messages();
            return Redirect::to('arti-kata/' . $term)->withErrors($validator)->withInput();
        }