Java Academy · Lesson

Bean Validation: @NotNull, @Size, @Pattern

Annotate DTOs with Bean Validation constraints and trigger validation with @Valid in controllers.

Lesson 1 of 413 steps

Bean Validation: @NotNull, @Size, @Pattern is a free Java Academy lesson on CoddyKit. This is lesson 1 of 4. You can read the complete lesson below for free — then practise it hands-on in the browser with a built-in code editor and a 24/7 AI tutor. It is part of the Java Academy learning path, and your progress syncs across the web and the CoddyKit app. The Java Academy course includes 4 lessons in total.

What Is Bean Validation?

Bean Validation (Jakarta Bean Validation 3.0) provides declarative constraint annotations for Java beans. Spring Boot auto-configures a validator and triggers it via @Valid or @Validated.

@NotNull, @NotEmpty, @NotBlank

@NotNull: value must not be null. @NotEmpty: not null and not empty (strings/collections). @NotBlank: not null, not empty, not whitespace-only. Prefer @NotBlank for strings.

public record CreateUserRequest(
    @NotBlank(message = "Name is required")
    String name,
    @NotBlank @Email
    String email,
    @NotNull
    UserRole role
) {}

@Size and @Length

@Size(min, max) constrains the size of strings, collections, maps, and arrays. @Length (Hibernate) works only on strings. Prefer @Size for portability.

@Size(min = 3, max = 50, message = "Name must be 3-50 characters")
private String name;
@Size(min = 1, max = 10, message = "Cart must have 1-10 items")
private List<CartItem> items;

@Min, @Max, @Positive, @Range

Numeric constraints: @Min/@Max for exact bounds, @Positive/@PositiveOrZero for sign constraints, @DecimalMin/@DecimalMax for BigDecimal.

@Min(1) @Max(100)
private int quantity;
@DecimalMin("0.01") @DecimalMax("99999.99")
private BigDecimal price;
@Positive
private long orderId;

@Pattern for Regex Validation

@Pattern(regexp) validates strings against a regular expression. Useful for phone numbers, zip codes, and custom formats.

@Pattern(regexp = "^\\+?[1-9]\\d{7,14}$", message = "Invalid phone number")
private String phone;
@Pattern(regexp = "^[A-Z]{2}\\d{5}$", message = "Invalid postal code (e.g. AB12345)")
private String postalCode;

@Email and @URL

@Email validates email format (basic RFC 5321). @URL (Hibernate) validates URL format. Always combine with @NotBlank since they allow null.

@NotBlank @Email
private String email;
// Hibernate-specific:
@URL(protocol = "https")
private String profileUrl;

@Past, @Future, @PastOrPresent

Temporal constraints validate date/time values. Works with LocalDate, LocalDateTime, Instant, and more.

@Past(message = "Birth date must be in the past")
private LocalDate birthDate;
@Future(message = "Expiry must be in the future")
private LocalDate expiryDate;

Triggering Validation with @Valid

Add @Valid to a controller method parameter. Spring validates the object and throws MethodArgumentNotValidException on failure, returning a 400 Bad Request.

@PostMapping("/users")
public ResponseEntity<UserDto> create(@Valid @RequestBody CreateUserRequest req) {
    User user = userService.create(req);
    return ResponseEntity.status(201).body(UserDto.from(user));
}

Cascading Validation with @Valid on Fields

To validate nested objects, annotate the field with @Valid in addition to the class-level constraints.

public record OrderRequest(
    @NotNull @Valid
    AddressRequest shippingAddress, // validates AddressRequest constraints too
    @Valid @NotEmpty
    List<@Valid LineItemRequest> items
) {}

Validation Groups

Use groups to apply different constraints in different contexts (e.g., Create vs Update). Annotate with the group interface and trigger with @Validated(CreateGroup.class).

public interface CreateGroup {}
public interface UpdateGroup {}
public record UserRequest(
    @NotBlank(groups = CreateGroup.class) String password,
    @NotNull(groups = UpdateGroup.class)  Long id
) {}
// Controller:
@PutMapping("/{id}")
public UserDto update(@Validated(UpdateGroup.class) @RequestBody UserRequest req) { ... }

Reading Validation Errors

Catch MethodArgumentNotValidException in a @ControllerAdvice to extract field errors and build structured error responses.

@ExceptionHandler(MethodArgumentNotValidException.class)
public ResponseEntity<Map<String, String>> handleValidation(MethodArgumentNotValidException ex) {
    Map<String, String> errors = new LinkedHashMap<>();
    ex.getBindingResult().getFieldErrors().forEach(e ->
        errors.put(e.getField(), e.getDefaultMessage()));
    return ResponseEntity.badRequest().body(errors);
}

Quick Check

Which annotation validates that a String is non-null AND non-blank (not just whitespace)?

Recap

Annotate DTOs with Bean Validation constraints. Add @Valid in controllers to trigger validation. Use @NotBlank for strings, @Size for lengths, @Pattern for regex, @Past/@Future for dates. Handle errors in @ControllerAdvice.

Free to start

Learn Java with an AI tutor — free

Write and run real code in your browser, get instant help from a 24/7 AI tutor, and pick up where you left off on the web or in the app.

Courses
104
Lessons
374

Frequently Asked Questions

Is the “Bean Validation: @NotNull, @Size, @Pattern” lesson free?

Yes — the full text of “Bean Validation: @NotNull, @Size, @Pattern” is free to read here on the web. To practise it interactively (a built-in code editor and a 24/7 AI tutor) and unlock the rest of the Java Academy course, upgrade to CoddyKit PRO. The Java Academy course includes 4 lessons in total.

What will I learn in “Bean Validation: @NotNull, @Size, @Pattern”?

Annotate DTOs with Bean Validation constraints and trigger validation with @Valid in controllers. You practise Java Academy with hands-on code you run directly in the browser, and a 24/7 AI tutor answers your questions as you work through the lesson.

Do I need any experience to start Java Academy?

No prior experience is required. Java Academy on CoddyKit is structured for beginners through advanced learners, so you can start here or from the beginning and move at your own pace. This is lesson 1 of 4.

How long does the “Bean Validation: @NotNull, @Size, @Pattern” lesson take?

Most CoddyKit lessons take about 5–10 minutes. Each one is bite-sized and interactive, so you make steady progress and pick up exactly where you left off across the web and the app.

Can I write and run code in this Java Academy lesson?

Yes. Every Java Academy lesson includes a built-in code editor, so you write and run real code right in your browser and get instant AI feedback — no local setup required.

All lessons in this course

  1. Bean Validation: @NotNull, @Size, @Pattern
  2. Custom Constraint Annotations
  3. Global Exception Handling with @ControllerAdvice
  4. RFC 7807 Problem Details and Consistent Error Responses
← Back to Java Academy