implementation 'org.springframework.boot:spring-boot-starter-validation'
| Annotation | 설명 |
|---|---|
| @NotNull | null 불가 |
| @NotEmpty | null, “” 불가 |
| @NotBlank | null, “”. “ “ 불가 |
| @Size | 문자 길이 측정 |
| @Max | 최대값 |
| @Min | 최소값 |
| @Positive | 양수 |
| @Negative | 음수 |
| E-mail 형식 | |
| @Pattern | 정규 표현식 |
RestController을 이용하여 @RequestBody를 가져올 때 검증하는 방법
@PostMapping("/validation")
@ResponseBody
public ProductRequestDto testValid(@RequestBody @Valid ProductRequestDto requestDto) {
return requestDto;
}
이때 Valid 조건에 대한 세부 사항은 requestDto 객체 내에 정의를 해 둔다
package com.sparta.springauth.dto;
import jakarta.validation.constraints.*;
import lombok.Getter;
@Getter
public class ProductRequestDto {
@NotBlank
private String name;
@Email
private String email;
@Positive(message = "양수만 가능합니다.")
private int price;
@Negative(message = "음수만 가능합니다.")
private int discount;
@Size(min=2, max=10)
private String link;
@Max(10)
private int max;
@Min(2)
private int min;
}