Validation 적용

꿀이·2022년 2월 1일
0
post-thumbnail

회원가입 양식 Validation 적용

일단은 email 빼고는 공백이 오지 못하도록 하자.

에러코드를 확인해보고 싶어서 로그를 한번 찍어봤고, 모두 공백으로 값을 넘겨보면 다음과 같이 에러코드를 확인할 수 있당, 요 에러코드를 error properties에 등록해서 에러코드랑 내가만든 메세지를 매핑시켜주자.

        if (bindingResult.hasErrors()) {
            List<ObjectError> allErrors = bindingResult.getAllErrors();
            for (ObjectError err : allErrors) {
                log.info("error={}", err);
            }
            return "members/createMemberForm";
        }

이제 회원양식 html 을 수정해주자. 입력양식에 문제가 발생했을때 빨간색 테두리와 에러 메세지를 띄워 줄꺼다..!!!

  • th:errorclass 를 통해서 필드에러가 발생하면 빨간색 css를 적용할 수 있다.
  • th:errors 를 통해서 만들어둔 properties 파일에서 메세지를 가져온다.
<div>
    <form class="container" action="/members/new" th:object="${memberForm}" method="post">
        <h1>회원 정보 입력</h1>
        <input type="text" th:field="*{userId}" th:errorclass="field-error" class="input" placeholder="ID" >
            <div class="field-error" th:errors="*{userId}">ID 입력 오류</div>
        <input type="text" th:field="*{userName}" th:errorclass="field-error" class="input" placeholder="이름" >
            <div class="field-error" th:errors="*{userName}">사용자 이름 입력 오류</div>
        <input type="text" th:field="*{password}" th:errorclass="field-error" class="input" placeholder="PASSWORD" />
            <div class="field-error" th:errors="*{password}">비밀번호 입력 오류</div>
        <input type="text" th:field="*{email}" th:errorclass="field-error" class="input" placeholder="EMAIL" />
        <input type="submit" value="제출">
    </form>
</div>


참고

한글 깨짐

아니... 이게 왜 깨지는거야 ㅠㅠ 라고 고민을 하고 있었는데 properties file 인코딩 설정도 변경을 해줬어야 했다.

errors.properties 경로 설정

여기에 메세지를 추가를 해줬는데 왜 디폴트 메세지가 나오지... 라고 생각하고 있었는데, application.properties에 basename에다가 errors를 추가해주니까 메세지 검색이 정상적으로 되는걸 확인할 수 있었다.

profile
내게 맞는 옷을 찾는중🔎

0개의 댓글