728x90

게시글 작성 및 수정 작업 중 @Valid 를 사용하지 않고 자바스크립트를 통해 form 데이터를 검증하도록 하였다.

관련 프로젝트 : https://black-mint.tistory.com/70

 

[Spring Boot] 게시글 작성, 수정

이전 파일 업로드 글과 연관지어 게시글 작성의 구현을 마무리하고 이를 정리하겠습니다. 파일첨부에 대해서는 언급하지 않겠습니다! 이전 글 : https://black-mint.tistory.com/62?category=982467 [Spring Boot].

black-mint.tistory.com


1. html 코드

			<form action="#" th:action="@{/board/form}" th:object="${board}" method="post" enctype="multipart/form-data"
				onsubmit="return checkForm(this);">
				<div class="mb-3">
					<label for="title" class="form-label">제목</label>
					<input type="text" class="form-control" id="title" th:field="*{title}">
				</div>
				<div class="mb-3">
					<label for="content" class="form-label">내용</label>
					<textarea class="form-control" id="content" rows="13" th:field="*{content}"></textarea>
				</div>

				<div class="nav justify-content-end mb-5">
					<button id="submit" type="submit" class="me-2 btn btn-primary">작성</button>
				</div>
			</form>
  • onsubmit을 이용해 form 양식 제출 시 값을 검증한다.
  • checkForm(this) : this를 넣어줌으로써 자바스크립트에서 form 태그에 담긴 데이터를 컨트롤하는데 용이

2. 검증 script 코드

		// form submit 검증
		function checkForm(form) {
			if (form.title.value == "") {
				alert('제목을 입력하세요.');
				form.title.classList.add('is-invalid');
				form.title.focus();
				return false;
			}

			if (form.content.value == "") {
				alert('내용을 입력하세요.');
				form.title.classList.remove('is-invalid');
				form.content.classList.add('is-invalid');
				form.content.focus();
				return false;
			}
			form.content.classList.remove('is-invalid');
			return true;
		}
  • 파라미터로 넘어온 form(this)를 이용해 값을 확인한다.
  • form.[name].value : 제출된 [name] 이름을 가진 element의 값
  • classList.add : 해당 태그에 클래스를 추가한다.
  • classList.remove : 해당 태그의 클래스를 제거한다.
  • focus() : 해당 태그로 커서를 옮긴다.
  • return false의 경우 서버로 값이 넘어가지 않음.

+ Recent posts