Spring Validation Concepts: Difference between revisions
Line 35: | Line 35: | ||
return "someView"; | return "someView"; | ||
} | } | ||
... | |||
// ... | |||
} | } | ||
} | } |
Revision as of 05:26, 12 October 2018
Internal
Overview
Spring supports Bean Validation API (JSR-303) which allows to declare validation rules as annotations, as opposed to explicitly writing validation logic in the application code. The Bean Validation API and the Hibernate implementation of the Validation API are automatically added to the project as transient dependencies of the Spring Boot web starter.
Bean Validation in Spring MVC
Applying bean validation in Spring MVC consists of:
Declare Validation Rules
Declare validation rules on the domain model data class that is to be validated. Annotate members of the domain model data classes with Bean Validation annotations @NotNull, @Size, @NotBlank, @Pattern, @Digits or Hibernate Validation annotations @CreditCardNumber
Configure Controller Methods for which Validation Should Be Performed
Designate controller methods for which validation should be performed by annotating the domain model data objects that forms bind to with @Valid. The validation is performed at form binding. Spring Validation provides an org.springframework.validation.Errors class that can be added to the controller method signature and whose instance carries validation error information inside the method, if validation failed:
@Controller
@RequestMapping(...)
public class SomeController {
@PostMapping
public String create(@Valid Taco taco, Errors errors) {
if (errors.hasErrors()) {
// return the logical name of the view that
// renders the form that produced the errors
return "someView";
}
// ...
}
}
Configure Forms to Display Validation Errors
Configuring the form views to display validation errors.
TODO
TODO:
- https://docs.spring.io/spring/docs/5.1.0.RELEASE/spring-framework-reference/core.html#validation
- https://docs.spring.io/spring/docs/5.1.0.RELEASE/spring-framework-reference/core.html#validation-beanvalidation
- JSR-303 validation, https://spring.io/guides/gs/validating-form-input/