Skip to content
javahacks.dev
Jakarta EE

Jakarta Bean Validation Explained With Constraints

Learn Jakarta Bean Validation: built in constraints, validating objects and methods, groups, cascading, custom constraints and messages.

6 min read
Summarize in AI
Flat illustration of a request passing through a servlet container, with the OpenJDK, Docker and Apache Tomcat logos.

Bean Validation is the standard way to declare what a valid object is. The annotations travel with the class, and every layer that cares can enforce them: the web layer on input, the persistence layer before a write, the service layer on method arguments. This guide explains Jakarta Validation 3.1 as in Jakarta EE 11, with Hibernate Validator 9 as the reference implementation. It covers declaring constraints, running the validator, validating method calls, groups, custom constraints and the rules about what should and should not be a constraint at all.

Declare constraints

java
public class NewCustomer {

    @NotBlank @Size(max = 80)
    private String name;

    @NotBlank @Email
    private String email;

    @Min(18) @Max(130)
    private int age;

    @Valid @NotNull
    private Address address;

    @NotEmpty
    private List<@NotBlank String> tags;
}

Constraints on records work the same way on the record components. List<@NotBlank String> is a container element constraint that applies to every entry in the list, and @Valid on the address cascades validation into the nested object. Without the cascade, the nested object's own constraints are ignored, which is the most common way a validation rule appears to do nothing.

ConstraintChecks
@NotNull, @NotBlank, @NotEmptyPresence, non-blank text, non-empty collection
@Size, @Min, @Max, @Positive, @PositiveOrZeroLength and numeric ranges
@Email, @PatternFormat
@Past, @Future, @PastOrPresentDates and times
@Digits, @DecimalMin, @DecimalMaxDecimal precision and bounds

Most constraints treat null as valid, so that each one checks one thing. Combine them with @NotNull where presence is required. @NotBlank is the exception worth remembering for text: it covers null, empty and whitespace-only values in one annotation, and it only applies to strings.

Validate

java
Validator validator = Validation.buildDefaultValidatorFactory().getValidator();
Set<ConstraintViolation<NewCustomer>> violations = validator.validate(customer);

for (ConstraintViolation<NewCustomer> v : violations) {
    System.out.println(v.getPropertyPath() + ": " + v.getMessage());
}
Text
email: must be a well-formed email address
address.zip: must match "[0-9]{5}"

The property path shows exactly where in the object graph the rule failed, including indexes for list elements. Building a validator factory is expensive, so create one and reuse it. In a container you inject Validator or rely on the integration: Jakarta REST resources validate @Valid parameters, JPA validates entities before persist and update, and Jakarta Faces validates bound properties. Spring does the same with @Valid, see validating request bodies, and Quarkus in validation.

Method validation

java
public class Transfers {

    public @NotNull Receipt move(@NotNull Account from, @NotNull Account to, @Positive BigDecimal amount) {
        // ...
    }
}

With the integration enabled, calls to a CDI bean or a Spring bean validate their arguments before the method runs, and the return value is validated afterwards. A failure throws ConstraintViolationException. This places the rule at the domain boundary rather than only in the web layer, so a batch job that calls the same service gets the same protection. The constraints also act as documentation: the signature states which arguments may be null and which amounts are legal.

Groups

java
public interface OnCreate { }
public interface OnUpdate { }

public class CustomerDto {

    @Null(groups = OnCreate.class) @NotNull(groups = OnUpdate.class)
    private Long id;

    @NotBlank(groups = {OnCreate.class, OnUpdate.class})
    private String name;
}

validator.validate(dto, OnCreate.class);

Groups pick a subset of constraints at validation time, so one class can carry the rules of two operations. They add complexity, and a reader must track which group applies where. Separate request types for create and update often read better and document the API more honestly.

A custom constraint

java
@Target({FIELD, PARAMETER})
@Retention(RUNTIME)
@Constraint(validatedBy = SkuValidator.class)
public @interface ValidSku {
    String message() default "{validation.sku}";
    Class<?>[] groups() default {};
    Class<? extends Payload>[] payload() default {};
}

public class SkuValidator implements ConstraintValidator<ValidSku, String> {

    private static final Pattern SKU = Pattern.compile("[A-Z]{2}-\\d{4}");

    @Override
    public boolean isValid(String value, ConstraintValidatorContext ctx) {
        return value == null || SKU.matcher(value).matches();
    }
}

Return true for null and let @NotNull decide about presence; that keeps the constraint composable. The message key is resolved from ValidationMessages.properties, which supports translations and parameters such as {min}. Test a validator as a plain class: it has no container dependency, so a unit test with five inputs, including null and the boundaries, is quick.

What belongs in a constraint

A constraint is a pure check on a value. Rules that need a database lookup, the current user or other aggregates belong in the service layer, where transactions and error handling exist. A uniqueness rule is the classic case: a validator that queries the table passes for both of two simultaneous requests, so the rule needs a unique index, and the service must translate the index violation into a clear error. Use constraints for shape, range and format, and code for business rules.

Messages and localisation

The default messages come from the implementation and are available in many languages, selected from the locale of the validator factory. Override them per constraint with the message attribute, or globally by supplying ValidationMessages.properties on the classpath. A message may interpolate attributes of the constraint, such as {min} and {max}, and the validated value as ${validatedValue}. Keep the messages user-facing: they usually reach a form. Put the technical detail, the property path and the invalid value, into your logs, not the message.

Validation in different layers

A rule stated once can run in three places without being repeated. The web layer validates the request body, so a bad request never reaches your code. The service layer validates method arguments, so internal callers are checked as well. The persistence layer validates before an insert or update, so nothing invalid is written even if both layers above were bypassed. This defence in depth has a cost, because a rule runs several times, so keep validators cheap. If the repeated checking is a concern, turn off the JPA lifecycle validation with jakarta.persistence.validation.mode=none after you have confirmed the layers above cover every entry point.

Testing constraints

Test a constraint class with a plain Validator and no container. Build the object with one invalid field, call validate, and assert on the violation's property path and message key. One test per constraint is enough, and a test with all fields valid proves that nothing else is flagged. These tests are fast, and they pin the rules so that a refactor of the class cannot silently drop an annotation.

Common mistakes

Forgetting @Valid on a nested object or a collection element skips the nested rules. Putting @NotNull on a primitive does nothing, because a primitive cannot be null. Using @Size on a number fails at validation time with an exception about no validator for that type. And relying on validation for security is a mistake: it checks shape, it does not authorise or sanitise.

Choosing constraints for a new field

When adding a field, decide four things: whether it is required, its size or range, its format and its relation to other fields. Write the constraints at once, add a test for the boundary values and mention the rule in the API documentation. A field added without constraints is the usual source of the first bad row in production, and fixing data later is more expensive than writing an annotation.

Where validation stops

Validation does not replace authorisation, and it is not a defence against injection by itself. Output encoding and parameterised queries are separate controls, covered in preventing XSS. The reference is the Jakarta Validation specification, and the Hibernate Validator guide documents the constraints.

Share

Keep reading

Get new posts by email

We send one email when a new post is published. No spam.

Unsubscribe in one click. No spam, ever.