Thymeleaf th:field, th:errorclass 속성

Yuri Lee·2021년 1월 6일
0
<form th:action="@{/customers/create}" th:object="${customerForm}" method="post">
  <input type="text" id="lastName" name="lastName" th:field="*{lastName}" th:errorclass="error-input" value="" />
  <span th:if="${#fields.hasErrors('lastName')}" th:errors="*{lastName}" class="error-messages">error!</span>
</form>

form 태그에 포함된 action속성 값을 th:action속성 값으로 치환할 수 있으며, th:object속성 값에 Model속성 이름을 지정하여 이 태그 안에서 *{필드이름} 형식으로 사용할 수 있다.

th:field="*{필드 이름}"을 설정하면 이 HTML필드와 폼 객체(여기서는 CustomerForm)에 포함된 필드를 연결할 수 있고 HTML필드 값이 폼 객체의 해당 필드로 설정된다. 반대로 폼 객체의 필드 값이 Model에서 HTML필드 값을 설정된다.

입력 검사에서 오류가 발견됐을 경우에는 th:errorclass속성 값이 class속성에 설정된다. 필드에 오류가 있을 경우에만 특정 태그를 표시하고 싶다면 해당 태그에 th:if="${#fields.hasErrors('필드이름')"을 설정한다. th:errors="*{필드이름}"을 설정하면 태그 안에 있는 문자열을 대상 필드에 관련된 에러 메시지로 치환할 수 있다.


출처: https://effectivecode.tistory.com/1056 [Mr.후]

profile
Step by step goes a long way ✨

0개의 댓글