Add spring-boot-starter-validation
Validation Starter no longer included in web starters
As of #19550, Web and WebFlux starters do not depend on the validation starter by default anymore. If your application is using validation features, for example you find that javax.validation.*
imports are not being resolved, you’ll need to add the starter yourself.
For Maven builds, you can do that with the following:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-validation</artifactId>
</dependency>
For Gradle, you will need to add something like this:
`dependencies {
...
implementation 'org.springframework.boot:spring-boot-starter-validation'
}`
// 복합객체 생략 가능
@ModelAttribute
Spring Validation
- validate the length
- validate the necessary value
Spring 3 introduces several enhancements to its validation support.
- the JSR-303 Bean Validation API is now fully supported.
- when used programmatically, Spring’s DataBinder can now validate objects as well as bind to them.
- Spring MVC now has support for declaratively validating @Controller inputs.
http://hibernate.org/validator/
JSR-303 Bean Validation API
Annotate domain model properties with declarative validation constraints and the runtime enforces them
Custom Validation
- validate the value from database and show the same page again when it has an error.
- Create SignUpFormValidator class
- Implement Validator interface (spring framework)
- Use SignUpFormValidator with @InitBinder inController
- @Valid Check if SignUpForm is entered.
// AccountController class
@PostMapping("/sign-up")
public String signUpSubmit(@Valid SignUpForm signUpForm, Errors errors) {
if (errors.hasErrors()) {
return "account/sign-up"; // return form
}
}
// SignUpFormValidator class
@Override
public void validate(Object object, Errors errors) {
// access to nickname, email field in database
SignUpForm signUpForm = (SignUpForm)object;
if (accountRepository.existsByEmail(signUpForm.getEmail())) {
errors.rejectValue("email", "invalid.email", new Object[]{signUpForm.getEmail()}, "이미 사용중인 이메일 입니다.");
}
if (accountRepository.existsByNickname(signUpForm.getNickname())) {
errors.rejectValue("nickname", "invalid.nickname", new Object[]{signUpForm.getEmail()}, "이미 사용중인 닉네임 입니다.");
}
}