Sub topic 3
Declaring constraints on a request DTO
A request DTO (data transfer object) is the class that carries the incoming JSON into your controller. This chapter covers how to declare rules on it with Jakarta Bean Validation constraint annotations. It also covers how null is treated, which types each constraint accepts, and the mistakes that make a rule silently do nothing.
This chapter assumes you know Java records and annotations, can write a basic Spring MVC controller, and can add a dependency in Maven or Gradle. The validation starter from the previous chapter is already on your classpath. Wiring @Valid into a controller comes in the next chapter. Here you only declare rules and check them with a plain Validator.
How a constraint is declared
A constraint is an annotation that states one rule about a value. You put it on the field, or for a record on the component, that holds the value. Bean Validation reads the annotations at runtime and produces a set of violations. A violation records the property path, the rejected value, and a message.
import jakarta.validation.constraints.Email;
import jakarta.validation.constraints.Min;
import jakarta.validation.constraints.NotBlank;
import jakarta.validation.constraints.NotEmpty;
import jakarta.validation.constraints.NotNull;
import jakarta.validation.constraints.Pattern;
import jakarta.validation.constraints.Size;
import java.util.List;
public record CreateUserRequest(
@NotBlank @Size(max = 50) String name,
@NotBlank @Email String email,
@NotNull @Min(18) Integer age,
@Pattern(regexp = "[A-Z]{2}") String country,
@NotEmpty @Size(max = 5) List<@NotBlank String> roles) {
}Several constraints on one component are all evaluated, and each failure is reported separately. They are combined with AND. There is no ordering guarantee between them unless you use groups or a group sequence, which a later chapter covers.
Annotations on record components
An annotation on a record component is copied to the generated field, accessor method, and constructor parameter, wherever the annotation's @Target allows. Hibernate Validator reads the field. The constraint annotations in jakarta.validation.constraints target fields, methods, parameters, and type uses, so they work on record components without extra setup. If you write your own constraint annotation, include ElementType.RECORD_COMPONENT or FIELD in its @Target, as the custom constraint chapter shows.
The standard constraints
The table lists the constraints you will use most often, with the types they accept.
| Constraint | Rule | Supported types |
|---|---|---|
| `@NotNull` | Value is not null | Any type |
| `@NotEmpty` | Not null and size above 0 | `CharSequence`, collections, maps, arrays |
| `@NotBlank` | Not null and has at least one non-whitespace character | `CharSequence` only |
| `@Size(min, max)` | Length or size within bounds | `CharSequence`, collections, maps, arrays |
| `@Min`, `@Max` | Numeric bound, inclusive | `BigDecimal`, `BigInteger`, `byte`, `short`, `int`, `long` and their wrappers |
| `@DecimalMin`, `@DecimalMax` | Bound given as a string, inclusive by default | Same as above, plus `CharSequence` |
| `@Positive`, `@PositiveOrZero`, `@Negative` | Sign check | Numeric types, including `float` and `double` |
| `@Digits(integer, fraction)` | Maximum digits before and after the decimal point | Numeric types and `CharSequence` |
| `@Pattern(regexp)` | Whole value matches the regular expression | `CharSequence` |
| `@Email` | Looks like an email address | `CharSequence` |
| `@Past`, `@PastOrPresent`, `@Future`, `@FutureOrPresent` | Date or time relative to now | `java.time` types, `Date`, `Calendar` |
| `@AssertTrue`, `@AssertFalse` | Boolean value | `boolean`, `Boolean` |
Pick the strongest constraint that matches your intent. For a required string, use @NotBlank, not @NotNull, because @NotNull accepts an empty string and a string of spaces.
Null is valid unless you say otherwise
This is the rule that causes the most confusion. Only @NotNull, @NotEmpty, and @NotBlank reject null. Every other constraint treats null as valid and skips the check. So @Min(18) Integer age accepts a missing age. You need @NotNull as well, as in the DTO above.
The same rule explains the pairing @NotBlank @Email. @Email alone would accept a missing email and also accept nothing else useful, since an empty string passes @Email too. The combination rejects null, empty, and blank values first, and then checks the format.
A missing JSON property and an explicit "age": null both reach the record as null. Jackson passes null for absent properties on records, so @NotNull covers both cases.
Primitives hide missing values
If you declare int age instead of Integer age, a missing property does not produce null. Jackson leaves the primitive at its default of 0 (unless configured to fail on null for primitives). @NotNull would never fire, and @Min(18) would report a misleading "must be at least 18" for a client that never sent the field. Use wrapper types for any required number or boolean in a request DTO so that "absent" stays distinguishable from "zero" or "false".
Checking constraints without Spring MVC
A DTO with constraints is an ordinary object, so you can validate it directly. This is the fastest way to learn what each constraint does, and it is the basis for the plain Validator tests covered later. The following program runs with only the validation starter on the classpath, which also supplies the expression language implementation that message interpolation needs.
import jakarta.validation.ConstraintViolation;
import jakarta.validation.Validation;
import jakarta.validation.Validator;
import jakarta.validation.ValidatorFactory;
import java.util.Comparator;
import java.util.List;
import java.util.Set;
public class ConstraintDemo {
public static void main(String[] args) {
try (ValidatorFactory factory = Validation.buildDefaultValidatorFactory()) {
Validator validator = factory.getValidator();
CreateUserRequest request = new CreateUserRequest(
" ", "not-an-email", 17, "de", List.of("ADMIN"));
Set<ConstraintViolation<CreateUserRequest>> violations = validator.validate(request);
violations.stream()
.sorted(Comparator.comparing(v -> v.getPropertyPath().toString()))
.forEach(v -> System.out.println(
v.getPropertyPath() + ": " + v.getMessage()
+ " (rejected: '" + v.getInvalidValue() + "')"));
}
}
}The output is:
age: must be greater than or equal to 18 (rejected: '17')
country: must match "[A-Z]{2}" (rejected: 'de')
email: must be a well-formed email address (rejected: 'not-an-email')
name: must not be blank (rejected: ' ')The validate method returns a Set, so the order is not defined. The sort above only makes the output stable.
Choosing and tuning constraints
Strings
@Size counts the value returned by length(), which is the number of UTF-16 code units. Most text matches the character count, but an emoji counts as 2. If the limit protects a database column, check how that column counts characters.
@NotBlank only checks the value. It does not trim it, so " Ada " passes and stays padded. Trim in your mapping code or service if you need clean data.
@Pattern must match the whole string, not a part of it. @Pattern(regexp = "[A-Z]{2}") rejects "DEU" and "de". You do not need ^ and $ anchors.
@Email is deliberately lenient. By default it accepts user@localhost, because the address is valid by the underlying rules without a top-level domain. If you need [email protected] as a minimum, add a pattern:
@NotBlank
@Email(regexp = "[^@\\s]+@[^@\\s]+\\.[a-zA-Z]{2,}")
String emailThe check is only for format. It does not prove that the mailbox exists. The only reliable test is to send a confirmation message.
Numbers
@Min and @Max take a long. For decimals such as prices, use @DecimalMin("0.00") with @Digits(integer = 8, fraction = 2) on a BigDecimal. Do not use @Min on float or double, which it does not support. Use @DecimalMin, @Positive, or @PositiveOrZero for those.
Collections
@NotEmpty on a list rejects null and an empty list. @Size limits the number of elements. To constrain the elements themselves, put the annotation on the type argument, as in List<@NotBlank String>. That is a container element constraint, and an invalid entry is reported with an indexed path such as roles[1].
Common errors
- A constraint on an unsupported type.
@NotBlank Integer ageor@Size(max = 3) int countfails at validation time with ajakarta.validation.UnexpectedTypeException("No validator could be found for constraint ... validating type ..."). The error appears on the first request, not at startup, so a test for each DTO catches it early. - A constraint that never runs. If the controller parameter lacks
@Valid, the annotations are never read. A DTO's constraints do nothing on their own, and that is the topic of the next chapter. - Missing
@NotNull. The rule@Min(18)alone lets a missing value through. - A hardcoded limit that differs from the database.
@Size(max = 50)on the DTO andVARCHAR(100)in the schema drift apart over time. Keep the numbers in one place, such as a shared constant, when you can.
Exercise
A DTO declares @Min(1) @Max(100) Integer quantity and @Email String contactEmail. A client sends {}. Does validation report any violation, and what would you add so that both fields are required? Also, what is the problem with changing Integer quantity to int quantity?
Show answer
No violation is reported, because @Min, @Max, and @Email treat null as valid and an empty JSON object leaves both fields null. Add @NotNull to quantity and @NotBlank to contactEmail. With int quantity, a missing property becomes 0 instead of null, so @NotNull can never fire. The client then gets a misleading "must be greater than or equal to 1" message, or if you removed @Min, an accidental 0 gets through.
Exercise
Why does @Size(max = 3) Integer count fail, and which constraints would you use to limit the value of an Integer?
Show answer
@Size applies to strings, collections, maps, and arrays, not numbers. Validation throws an UnexpectedTypeException because no validator exists for that type. To limit an Integer's value, use @Min and @Max, or @Positive and @PositiveOrZero for sign checks.