125. Java Bean Validation - dkkahm/study-springfamework5 GitHub Wiki

Annotations

  • @Null
  • @NotNull
  • @AssertTrue
  • @AssertFalse
  • @Min
  • @Max
  • @DecimalMin
    • Value is larger
  • @DecimalMax
    • Value is less than
  • @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
    • inclusive
  • @SafeHtml
  • @UniqueElements
  • @Url

Request with Validation

  • Post
    @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
    @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"));
    }