Skip to content
javahacks.dev
Quarkus

Quarkus Validation With Bean Validation Constraints

Validate input in Quarkus with Hibernate Validator: constraints on request records, Valid on resources, method parameters and a custom error response.

6 min read
Summarize in AI
Flat illustration of startup time of a JVM compared with a native image, with the Quarkus, Spring, Kubernetes and Spring Boot logos.

Quarkus supports Jakarta Validation, the same standard as Spring. This is Quarkus 3 with Hibernate Validator.

Add the extension

XML
<dependency>
  <groupId>io.quarkus</groupId>
  <artifactId>quarkus-hibernate-validator</artifactId>
</dependency>

The REST extension detects it and enables validation of resource parameters. Without it, @Valid and constraints do nothing, a point that a test with an invalid body should catch.

Constrain the request

java
public record NewUser(
        @NotBlank @Size(max = 60) String name,
        @Email @NotBlank String email,
        @Min(18) int age) { }
java
@POST
@Path("/users")
public RestResponse<User> create(@Valid NewUser body) {
    return RestResponse.status(Response.Status.CREATED, users.create(body));
}

An invalid request yields a 400 with a body like:

JSON
{
  "title": "Constraint Violation",
  "status": 400,
  "violations": [
    {"field": "create.body.email", "message": "must be a well-formed email address"}
  ]
}

The shape is Quarkus's default, with the field path including the method name. If you prefer a custom body, map the exception:

java
@ServerExceptionMapper
public RestResponse<Map<String, Object>> invalid(ConstraintViolationException e) {
    var errors = e.getConstraintViolations().stream()
            .collect(Collectors.toMap(v -> v.getPropertyPath().toString(), ConstraintViolation::getMessage, (a, b) -> a));
    return RestResponse.status(Response.Status.BAD_REQUEST, Map.of("errors", errors));
}

The same consideration for Spring is in validating request bodies.

Validate method arguments on any bean

java
@ApplicationScoped
public class Transfers {
    public void move(@NotNull Account from, @NotNull Account to, @Positive BigDecimal amount) { ... }
}

ArC adds an interceptor that validates the arguments before the call. This puts the check at the domain boundary instead of the web layer, so a message listener that calls the same method gets the same protection. A failure raises ConstraintViolationException.

Groups and cascading

@Valid on a field cascades into nested objects, and groups let create and update differ: @Valid triggers the default group, and @ConvertGroup or the @Validated-style options are limited, so separate request records for create and update are usually clearer.

Custom constraints

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

The validator class implements ConstraintValidator<ValidSku, String>. Constraints that need to query a store should call a CDI bean, but a uniqueness check that races with another request still needs a unique index. Jakarta Validation explained has the full model.

What to put in a constraint

A constraint should be a pure function of the value: a length, a pattern, a range, a checksum. That makes it cheap to run, easy to test with a plain validator instance, and safe to reuse on records, entities and method parameters. If a rule needs a database lookup, an external call or the current user, it belongs in the service layer, where a transaction and error handling exist. Mixing the two turns validation into hidden business logic that fails in surprising places.

How a failure looks to a client

By default, a failed validation on a REST endpoint returns a 400 with a JSON body that lists the violations: the field path, the message and the class. That body is easy for a client to read and leaks your parameter names and class names, which is information you might not want public. Customize it with an exception mapper for ConstraintViolationException, and return the shape your API uses everywhere, such as the problem details format, so that clients handle validation failures with the same code as every other error. Keep the field paths, since they are what a form needs to highlight the right input.

Messages and localization

Constraint messages come from a resource bundle, and Quarkus resolves them using the request's locale, so you can ship translations in ValidationMessages_fr.properties and have French users see French messages. Write messages as sentences with placeholders, must be at most {max} characters, and let the framework fill the numbers, so that a change to the limit changes the text. A message that repeats the field name is redundant, because the field is already reported next to it.

Validate at the edge and in the domain

Bean Validation on request objects checks shape: required fields, lengths, formats. It does not know whether an email is already taken or whether a product is in stock, and those rules belong in the service, reported as a conflict or a business error. Putting database lookups inside a custom constraint validator looks tidy, and it hides a query behind an annotation that runs on every validation, including in tests that never expected a database. Keep validators pure, and keep rules that need data in the service.

Method validation on beans

Annotating the parameters of a method on a CDI bean with constraints, as the extension supports, validates calls from anywhere, not only from REST. It is a good way to protect a service method that several endpoints and a message consumer all call. The failure is a ConstraintViolationException thrown by an interceptor, which means a call from inside the same class bypasses the check, the same limitation as every interceptor.

Performance and the validator

Validation of ordinary objects costs microseconds, and it is rarely a concern. Large collections are the exception: cascading validation with @Valid over a list of a hundred thousand items visits each one, so cap the size of lists in the request with @Size(max = ...) first, which is also a protection against oversized input. Build one validator and reuse it, since creating a validator factory per call is slow, and Quarkus injects a shared instance.

Testing the constraints

Test a custom constraint with the validator on its own, without the container: build a Validator, validate an object and assert the violations. Test the endpoint once with an invalid body and assert the 400 and the shape of the response. The unit test covers the rule, and the endpoint test covers the wiring.

Common mistakes

Forgetting @Valid on the request body parameter means nothing is validated, and the constraints on the class are decorations. Putting @NotNull on a primitive does nothing, because a primitive cannot be null, and @NotBlank on a number is a startup error. Using @Size on a Long fails, since it applies to strings and collections, and @Min and @Max are the number constraints. A test with an invalid body for each endpoint catches all of these, and takes a minute to write.

Cross-field rules

Constraints on one field cannot express "the end date must be after the start date". Put a constraint on the class instead, with a custom annotation and a validator that receives the whole object, or use a method annotated with @AssertTrue that returns whether the combination is valid. Name the method so that the error message reads well, because the property path in the response will include its name. Keep these rules free of any lookup, so they run fast and behave the same in every test, and report the failure on the field the user should fix.

Where this does not apply

Validation covers shape and simple rules at the edge. Authorization, state-dependent rules and uniqueness belong in the service and the database. For JSON that fails to parse, the error comes earlier, from the serializer. The REST side is in building an API. The reference is the Quarkus validation guide, and Hibernate Validator documents every built-in constraint.

Also inSpring MVC
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.