본문으로 바로가기

Form Data 유효성 검사

category [ Web 관련 ]/Laravel 2021. 6. 22. 17:06

Controller.php

use Illuminate\Http\Request;
use Illuminate\Support\Facades\Validator;


public function test(Request $request)
{

        $validator = Validator::make($request->all(), [
           'in_name'=>'required',
           'in_hp'=>'required',
        ]);


        if ($validator->fails()) {
            return response()->json(array('msg'=> 'Missing required items'), 400);
        }
        
}

 

blade.php

<meta name="csrf-token" content="{{ csrf_token() }}">

<script>
let sendData = $("form[name=frm]").serialize() ;
$.ajax({
            //아래 headers에 token을 추가
            headers: {'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')},
            type: 'put',
            url: '/counsel/inbound/api/update',
            dataType: 'json',
            data: sendData,
            success: function(data) {
                //console.log('success');
                console.log(data);
            },
            error: function(request, status, error) {
                let jsonObj = JSON.parse(request.responseText);
                alert(jsonObj['msg']);
                //console.log(json['msg']);
                //console.log("code:"+request.status+"\n"+"message:"+request.responseText+"\n"+"error:"+error);
            },
            complete : function(data) {}
});
</script>