Spring Boot Bootcamp – Workbooks and Challenges
)}

Cheat Sheet

This cheat sheet contains important takeaways from section three.

Field Validation

HeadHead
@NotBlankat least one non-whitespace character
@Mincannot be less than the minimum
@Maxcannot exceed the maximum
@NotEmptycannot be null or empty
@Emailwell-formed email address
@Sizesize must be between boundary
@AssertTruemust equal true
@Pastis in the past
@Futureis in the future
@Size(min = 2, message = "Username is too short")
  • @Valid: validates the fields of the object.
  • BindingResult: carries the result of the validation
  • th:errors: displays the error message for a violated field.
@PostMapping(value="path") public String postMethodName(@Valid Object object, BindingResult result)

Attention: You must define the BindingResult after Valid.

Custom Constraint Annotation


  • @interface: defines a custom annotation.
  • @Target(FIELD): target of your annotation is a field.
  • @Retention(RUNTIME): retains annotation during the runtime.
  • @Constraint(validatedBy = Validator.class): connects the constraint to a validator.
@Target({ElementType.METHOD, ElementType.FIELD}) @Retention(RetentionPolicy.RUNTIME) @Constraint(validatedBy = Validator.class) public @interface AnnotationName { //default message if constraint is violated String message() default "Invalid Data"; //boilerplate parameters. Class<?>[] groups() default {}; Class<? extends Payload>[] payload() default {}; }

Validator: implements the ConstraintValidator interface.

public class Validator implements ConstraintValidator<Annotation Type, ValidationType> { @Override public boolean isValid(ValidationType value, ConstraintValidatorContext context) { return true OR false; } }

Spring Boot uses your definition of isValid to validate the custom annotated field.

Cross-Field Validation

BindingResult.reject(String field, String errorCode, String errorMessage): rejects a field value and adds an error to the BindingResult.

Feedback Summary
5.0
3 students
5

100%
4

0%
3

0%
2

0%
1

0%
Written Reviews
There are no written reviews yet.