2019-03-15
우선 Laravel에서 사용되는 validation의 과정에 대해서 간단히 설명 해보면,
예를들어 POST방식으로 넘어온, title,body라는 값이 있다. 해당 값들을 처리해주는 소스의 윗단에 아래와 같은 소스를 넣으면,
$validatedData = $request->validate([
    'title' => 'required|unique:posts|max:255',
    'body' => 'required',
]);
해당 값이 제대로 됐는지 여부를 체크한 뒤, 제대로 된 값이 들어오지 않으면, 에러메세지를 리턴해준다.
그리고 그런 에러메세지를 view에서 아래와 같이 잡아주면 된다.
<input id="title" type="text" class="form-control{{ $errors->has('title') ? ' is-invalid' : '' }}" name="title" value="{{ old('title') }}" required autofocus>

@if ($errors->has('title'))
	<span class="invalid-feedback" role="alert">
		<strong>{{ $errors->first('title') }}</strong>
	</span>
@endif
넘어온 에러가 있으면, 해당 input오브젝트에 css를 새로 지정하고, 에러 메세지를 출력하면 되는 것이다.

자 그러면, ajax로 해당 부분을 어떤식으로 바꾸서 쓰는지 일단 소스를 보자.
<input type="text" id="title">
<input type="text" id="body">
<button type="button" id="save_btn">저장</button>

<script type="text/javascript">
function ajax_error(jsonData){
	if( typeof jsonData.errors != 'undefined' ){
		// console.log(jsonData.errors)
		$('.feedback_red').remove()
		$.each(jsonData.errors, function(k,v){
			$('#'+k).after("<div class='feedback_red'>"+v[0]+"</div>")
		})

		return true
	}
	else if( typeof jsonData.message != 'undefined' ){
		switch(jsonData.message){
			case "Unauthenticated.":
				location.href="/"
			break;

			default:
			alert("An unknown error has occurred.")
		}
	}
}

function reg_comment(){
	var tmp1 = {
		title: $('#title').val()
		,body: $('#body').val()
	}

	$.ajax({
		type: 'post'
		,url: 'ajax_url'
		,data: tmp1
		,success: function(data){
			console.log(data)
		}
		,error: function(xhr, status, msg){
			ajax_error(xhr.responseJSON)
		}
	});
}


$(function(){
	$('#save_btn').click(function(){
		reg_comment()
	})
})
</script>
필자의 블로그가 Laravel로 되어있질 않아서, 실제 결과물을 보여 줄 수 없기에 설명만 해주면.
우선, ajax로 값을 넘기고 유효성 검사에서 걸리게 될 경우 json으로 아래처럼 값이 리턴된다.
title,body의 input오브젝트에 아무것도 넣지 않고 '저장'버튼을 눌렀을때이다.
{
	"message":"The given data was invalid.",
	"errors":{
		"title":["\ud544\uc218 \uc785\ub825 \uac12\uc785\ub2c8\ub2e4."],
		"body":["\ud544\uc218 \uc785\ub825 \uac12\uc785\ub2c8\ub2e4."]
	}
}
유효성 체크에 걸린 값과, 해당 에러 메세지가 온다. (에러메세지는 한글로 "필수 입력 값입니다."여서 저렇게 표시된다)
ajax의 satus code가 422이기 때문에, error쪽으로 리턴된다.
위의 예저처럼 ajax_error()함수에서 되돌아온 error 메세지에 따라서 여러가지 연산을 줄 수 있게 된다.
그다음은 연산에 따라서, 해당 input오브젝트에 에러 표시를 해주면 되는 것이다.