125. Java Bean Validation - dkkahm/study-springfamework5 GitHub Wiki
Annotations
- @Null
- @NotNull
- @AssertTrue
- @AssertFalse
- @Min
- @Max
- @DecimalMin
- @DecimalMax
- @Negative
- Value is less than zero. Zero is invalid
- @NegativeOrZero
- @Positive
- @PositiveOrZero
- @Size
- check if string or collection is between a min and max
- @Digits
- check for integer digits and fraction digits
- @Past
- @PastOrPresent
- @Future
- @FutureOrPresent
- @Pattern
- @NotEmpty
- check if value is null or empty (whitespace characters or empty collection)
- @NotBlank
- check string is not null or not whitespace characters
- @Email
- @ScriptAssert
- Class level annotations, checks class against script
- @CreditCartNumber
- @Currency
- @DurationMax
- @DurationMin
- @EAN
- @ISBN
- @Length
- @CodePointLength
- @LuhnCheck
- @Mod10Check
- @Mod11Check
- @Range
- @SafeHtml
- @UniqueElements
- @Url
Request with Validation
@PostMapping("recipe")
public String saveOrUpdate(@Valid @ModelAttribute('recipe') RecipeCommand command, BindingResult bindingResult) {
if(bindingResult.hasError()) {
bindingResult.getAllErrors().forEach(objectError -> log.debug(objectError.toString()));
return RECIPE_RECIPEFORM_URL;
}
RecipeCommand savedCommand = recipeService.saveRecipeCommand(command);
return "redirect:/recipe/" + savedCommand.getId() + "/show";
}
@Test
public void testPostNewRecipeFormValidationFail() throws Exception {
RecipeCommand command = new RecipeCommand();
command.setId(2L);
when(recipeService.saveRecipeCommand(any())).thenReturn(command);
mvcMvc.perform(post("/recipe")
.contentType(MediaType.APPLICATION_FORM_URLENCODED)
.param("id", "")
.param("description", "some string")
)
.andExpect(status().isOk())
.andExpect(model().attributeExists("recipe"))
.andExpect(view().name("recipe/recipeform"));
}