Skip to main content
Advertisement

6.2 Basic Annotations

In Spring Boot, by adding the spring-boot-starter-validation dependency to your build tool, you can immediately use various Bean Validation annotations.

These are the most frequently used string validation annotations. It's important to know the differences between these three.

  • @NotNull: The field value must not be null. An empty string ("") or whitespace (" ") is allowed.
  • @NotEmpty: Must not be null and the length must be greater than 0. In other words, "" is not allowed, but " " (a block of whitespace) is allowed. For collections, it means the size must be greater than 0.
  • @NotBlank: Does not allow null, empty strings (""), or strings containing only whitespace (" "). This is the strongest and most commonly used annotation for string validation.
@NotBlank(message = "Please enter a title.")
private String title;
  • @Min(value) / @Max(value): Validates the specified minimum/maximum values (inclusive).
  • @Positive / @PositiveOrZero: Validates whether it is a positive number (> 0), or a positive number including zero (>= 0).
  • @Negative / @NegativeOrZero: Validates whether it is a negative number.
@Positive(message = "Price must be a positive number.")
private int price;

Format and Size Validation

  • @Email: Checks if it's a properly formatted email address.
  • @Size(min, max): Checks if the length of a string, or the size of a collection or array, is within the specified range.
  • @Pattern(regexp): Validates against a specified regular expression (Regex). Mostly used for checking password or phone number formats.
@Email(message = "Invalid email format.")
private String email;

@Pattern(regexp = "^01(?:0|1|[6-9])[.-]?(\\d{3}|\\d{4})[.-]?(\\d{4})$", message = "Does not match the mobile phone number format.")
private String phoneNumber;

After specifying these constraints in your DTO class, you can apply them by adding @Valid when receiving the parameter in a Controller's handler method.

@PostMapping("/signup")
public ResponseEntity<?> signup(@Valid @RequestBody SignupRequest request) {
// Only valid data that passes validation enters this area
return ResponseEntity.ok().build();
}
Advertisement