Video in progress

Junior 🌱 Spring

How does Bean Validation (@Valid, @NotBlank, @Size) work in Spring?

You put constraint annotations on DTO fields and write @Valid on the controller parameter. Spring validates the request before it reaches the method and returns 400 if something is wrong.

📖 Answer

You need spring-boot-starter-validation (Hibernate Validator) on the classpath.

public record RegisterRequest(
        @NotBlank @Size(max = 100) String name,
        @NotBlank @Pattern(regexp = "\\+998\\d{9}") String phone,
        @Email String email,
        @Min(16) int age) {}

@PostMapping("/api/register")
public UserDto register(@Valid @RequestBody RegisterRequest req) { ... }

If validation fails, the method isn't called at all — a MethodArgumentNotValidException is thrown and Boot turns it into a 400.

Where people often get confused:

  • @NotNull — must not be null, but "" gets through; @NotEmpty — must not be empty either; @NotBlank — must not consist only of whitespace either. Interviewers love asking about these three.
  • To validate a nested object too, you put @Valid on the field.
  • To validate @PathVariable/@RequestParam, before Spring 6.1 you needed @Validated on the class; in 6.1+ method validation is built in.

Validation catches client mistakes early. Business rules (for example, "email already taken") are still checked in the service.