검증(Validation) - 구현

junheelee·2022년 11월 2일
0

SpringMVC

목록 보기
18/19

검증의 역할:

컨트롤러의 중요한 역할은 HTTP 요청이 정상인지 검증하는 것

📋 주요 검증 로직

  • 상품 이름은 반드시 들어가야한다.
  • 가격은 1,000원 ~ 1,000,000원 사이의 값이여야 한다.
  • 수량은 9,999개를 넘을 수 없다

검증 1 - controller

@PostMapping("/add")
public String addItem(@ModelAttribute Item item, RedirectAttributes redirectAttributes, Model model) {
        //검증 오류 결과 보관
        Map<String, String> errors = new HashMap<>();
        //특정 필드 검증 로직
        if(!StringUtils.hasText(item.getItemName())) {
            errors.put("itemName", "상품 이름은 필수 입니다.");
        }
        if(item.getPrice() == null || item.getPrice() < 1000 || item.getPrice() > 1000000) {
            errors.put("price", "가격은 1천원에서 100만원 사이의 값을 입력해주세요.");
        }
        if(item.getQuantity() == null || item.getQuantity() >=9999) {
            errors.put("quantity", "수량은 9999개를 넘을 수 없습니다." );
        }
        //특정 필드가 아닌 복합 룰 검증
        if(item.getPrice() != null && item.getQuantity() != null) {
            int resultPrice = item.getPrice() * item.getQuantity();
            if (resultPrice < 10000) {
                errors.put("globalError", "가격 * 수량의 합은 10,000원 이상이여야 합니다. (현재입력: " + resultPrice + ")");
            }
        }
        //검증 조건 미충족시 다시 입력 폼으로
        if(!errors.isEmpty()) {
            log.info("errors = {}", errors);
            model.addAttribute("errors", errors);
            return "validation/v1/addForm";
        }
        //성공 로직
        Item savedItem = itemRepository.save(item);
        redirectAttributes.addAttribute("itemId", savedItem.getId());
        redirectAttributes.addAttribute("status", true);
        return "redirect:/validation/v1/items/{itemId}";
    }	

검증 1 - HTML

global error 출력

<div th:if="${errors?.containsKey('globalError')}">
     <p class="field-error" th:text="${errors['globalError']}">전체 오류 메세지</p>
</div>

상품명 error 출력

<div>
    <label for="itemName" th:text="#{label.item.itemName}">상품명</label>
    <input type="text" id="itemName" th:field="*{itemName}" th:class="${errors?.containsKey('itemName')} ? 'form-control field-error' : 'form-control'"
           class="form-control" placeholder="이름을 입력하세요">
        </div>
<div th:if="${errors?.containsKey('itemName')}">
    <p class="field-error" th:text="${errors['itemName']}">상품명 입력 오류 메세지</p>
</div>
//itemName에 해당하는 부분을 원하는 에러로그에 맞게 입력

검증 순서

  1. 화면 단에서 controller로 데이터 받아오기
  2. 받아온 데이터에 대한 검증

표현식

"${errors?.containsKey('keys')} ? 'form-control
field-error' : 'form-control'"

==

if (errors.contaionKey('key') == true {
		form-control + field-error 
}else {
		form-control
}
profile
Study of beginner dev

0개의 댓글