@Valid 어노테이션으로 Parameter 검증
java.validation 어노테이션
@AssertTrue: 주석이 달린 부울 값이 참인지 확인합니다.
@AssertTrue
private boolean example;
@AssertFalse: 주석이 달린 부울 값이 거짓인지 확인합니다.
@AssertFalse
private boolean example;
@Min: 주석이 달린 요소가 숫자이고 해당 값이 지정된 최소값보다 크거나 같은지 확인합니다.
@Min(0)
private int example;
@Max: 주석이 달린 요소가 숫자이고 해당 값이 지정된 최대값보다 작거나 같은지 확인합니다.
@Max(100)
private int example;
@DecimalMin: 주석이 달린 요소가 십진수이고 해당 값이 지정된 최소값보다 크거나 같은지 확인합니다.
@DecimalMin("0.0")
private BigDecimal example;
@DecimalMax: 주석이 달린 요소가 십진수이고 해당 값이 지정된 최대값보다 작거나 같은지 확인합니다
@DecimalMax("10.0")
private BigDecimal example;
@Negative: 주석이 달린 요소가 숫자이고 해당 값이 음수인지 확인합니다.
@Negative
private int example;
@NegativeOrZero: 주석이 달린 요소가 숫자이고 해당 값이 음수 또는 0인지 확인합니다.
@NegativeOrZero
private int example;
@Positive: 주석이 달린 요소가 숫자이고 해당 값이 양수인지 확인합니다.
@Positive
private int example;
@PositiveOrZero: 주석이 달린 요소가 숫자이고 해당 값이 양수 또는 0인지 확인합니다.
@PositiveOrZero
private int example;
@Size: 주석이 달린 요소(컬렉션, 배열 또는 문자열)의 크기가 지정된 범위 내에 있는지 확인합니다.
@Size(min = 2, max = 10)
private List<String> example;
@Digits: 주석이 달린 요소가 지정된 총 자릿수와 지정된 소수 자릿수를 가진 숫자 값인지 확인합니다.
@Digits(integer = 5, fraction = 2)
private BigDecimal example;
@Past: 주석이 달린 날짜/시간 값이 과거인지 확인합니다.
@Past
private Date example;
@PastOrPresent: 주석이 달린 날짜/시간 값이 과거 또는 현재인지 확인합니다.
@PastOrPresent
private LocalDateTime example;
@Future: 주석이 달린 날짜/시간 값이 미래인지 확인합니다.
@Future
private Date example;
@FutureOrPresent: 주석이 달린 날짜/시간 값이 미래 또는 현재인지 확인합니다.
@FutureOrPresent
private LocalDateTime example;
@Pattern: 주석이 달린 문자열 값이 지정된 정규식 패턴과 일치하는지 확인합니다.
@Pattern(regexp = "[A-Za-z]+")
private String example;
@Null: 주석이 달린 요소가 null인지 확인합니다.
@Null
private String example;
@NotNull: 주석이 달린 요소가 null이 아닌지 확인합니다.
@NotNull
private String example;
@NotEmpty: 주석이 달린 요소가 null이 아니고 비어 있지 않은지 확인합니다.
@NotEmpty
private List<String> example;
@NotBlank: 주석이 달린 문자열 값이 공백이 아니라 비어 있지 않고 null이 아닌지 확인합니다.
@NotBlank
private String example;
@Email: 주석이 달린 문자열 값이 유효한 이메일 주소인지 확인합니다.
@Email
private String example;
예제
UserLoginRequestDto.java
public class UserLoginRequestDto {
@NotNull
private String name;
@NotBlank
private String email;
// Getters and setters
}
UserController.java
import org.springframework.http.HttpStatus;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import javax.validation.Valid;
@RestController
@RequestMapping("/users")
@Validated
public class UserController {
@PostMapping("/login")
@ResponseStatus(HttpStatus.OK)
public void loginUser(@RequestBody @Valid UserLoginRequestDto requestDto) {
// Process the user login request
}
}
////요청
POST /users/login
Content-Type: application/json
{
"name": "John Doe",
"email": "john@example.com"
}
////결과
HTTP/1.1 200 OK
////요청
POST /users/login
Content-Type: application/json
{
"name": null,
"email": ""
}
////결과
HTTP/1.1 400 Bad Request
Content-Type: application/json
{
"timestamp": "2023-07-15T10:00:00Z",
"status": 400,
"error": "Bad Request",
"message": "Validation failed for object='userLoginRequestDto'. Error count: 2",
"path": "/users/login",
"details": [
{
"field": "name",
"message": "must not be null"
},
{
"field": "email",
"message": "must not be blank"
}
]
}
Jakarta Bean Validation specification
BeanNode, PropertyNode and ContainerElementNode host getContainerClass() and getTypeArgumentIndex(). If the node represents an element that is contained in a container such as Optional, List or Map, the former returns the declared type of the container and
beanvalidation.org
검증 - Bean Validation
JSR-380에 등재된 Bean Validation 2.0 이라는 표준 기술이다.즉, 검증을 위한 애노테이션과 여러 인터페이스를 어떻게 구현해야하는지 가이드가 기술되어 있다.Bean Validation을 구현한 구현체중 일반적
velog.io
[SPRING] @Valid @Validated 사용하기 - java bean validation
😎서론 이전에는 @Valid 가 어떻게 흘러가는지 알아봤다면 이번에는 사용하는 방법에 대해서 간략하게 적어보려 한다. 이전 글 - [SPRING] @Valid 어떻게 동작할까 - java bean validation 목차 - @Valid 사용
kdhyo98.tistory.com