Skip to content

Validation

Damian Malczewski edited this page Sep 10, 2026 · 1 revision

Validation

The validation feature translates schema keywords into jakarta.validation (Jakarta Bean Validation) constraint annotations, so a bound DTO can be checked by a Validator - one that you, or a framework such as Spring Boot, invokes. The annotations alone enforce nothing, see below.

modelmaker {
    features {
        validation { enabled = true }
    }
}

The keywords are always parsed; with the feature off they are simply not emitted.

Structural constraints

  • A property that is required, or that has a default - @NotNull(message = "must not be null").
  • A property that is a $ref to a generated type, or an inline nested object - @Valid.
  • An element of a List that is a generated type - @Valid in the container-element position.

@Valid is not added for a $ref to a JDK type such as java.time.Instant - there is nothing generated to cascade into.

Keyword mapping

On a string:

  • pattern - @Pattern(regexp = ...), message must match "<regexp>".
  • enum - a @Pattern alternation over the values, message must be one of A, B, C.
  • format: "email" - @Email, message must be a well-formed email address.
  • format: "decimal" - @Pattern, message must be a decimal number.
  • format: "date" - @Pattern, message must be a date in yyyy-MM-dd format.
  • format: "time" - @Pattern, message must be a time in HH:mm:ss format.
  • format: "date-time" - @Pattern, message must be an ISO-8601 date-time.
  • format: "uuid" - @Pattern, message must be a UUID.
  • minLength / maxLength - @Size(min = , max = ), message size must be between X and Y, or size must be at least X / size must be at most Y when only one bound is given.

On a number:

  • minimum / maximum on an integer - @Min(value = ) / @Max(value = ), messages must be greater than or equal to X and must be less than or equal to Y.
  • minimum / maximum on a number, or on a string with format: "decimal" - @DecimalMin(value = "") / @DecimalMax(value = ""), with the same wording.

On an array:

  • minItems / maxItems - @Size on the List itself, with the same size must be ... wording as minLength / maxLength.

Messages are hardcoded into the generated annotation - no ValidationMessages.properties bundle is needed, and no message key is emitted.

Precedence between pattern sources

A property gets one @Pattern. When more than one source applies:

  1. An explicit pattern wins, and keeps the must match "..." message.
  2. Otherwise an enum alternation.
  3. Otherwise the regex implied by a string format.

format: "email" is separate - it produces @Email, not a @Pattern, so it can coexist with an explicit pattern.

enum

"status": { "type": "string", "enum": ["ACTIVE", "SUSPENDED"] }
@Pattern(regexp = "^(\\QACTIVE\\E|\\QSUSPENDED\\E)$", message = "must be one of ACTIVE, SUSPENDED")
public @Nullable String getStatus() {
  return status;
}

Values are quoted with Pattern.quote, so a value containing regex metacharacters is matched literally. An enum does not become a Java enum - see Property Types.

Lists

An array's own keywords size the List; keywords written inside "items" become container-element annotations:

"tags": {
  "type": "array",
  "maxItems": 10,
  "items": { "type": "string", "minLength": 1, "maxLength": 40, "pattern": "^[a-z-]+$" }
}
@Size(max = 10, message = "size must be at most 10")
public @Nullable List<@Pattern(regexp = "^[a-z-]+$", message = "must match \"^[a-z-]+$\"") @Size(min = 1, max = 40, message = "size must be between 1 and 40") String> getTags() {
  return tags != null ? Collections.unmodifiableList(tags) : null;
}

Element annotations never include @NotNull. They render at the same site as the property's own constraints - the constructor and the builder keep the plain List<T>.

Order on a member

Annotations are emitted in a stable order: @NotNull, @Valid, the array @Size, then @Email, @Pattern, @Size (length), @Min, @Max, @DecimalMin, @DecimalMax.

Placement

By default constraints sit on the getters, matching where jackson puts @JsonProperty. See Feature Configuration.

Warning

Setting both annotateFields and annotateGetters emits every constraint twice, and Hibernate Validator will report every violation twice.

Runtime dependencies

dependencies {
    implementation("jakarta.validation:jakarta.validation-api:3.1.1")
    implementation("org.hibernate.validator:hibernate-validator:9.1.3.Final")
}

The API alone is enough to compile; an implementation is needed to actually validate.

try (ValidatorFactory factory = Validation.buildDefaultValidatorFactory()) {
  Set<ConstraintViolation<Customer>> violations = factory.getValidator().validate(customer);
}

Nothing validates on your behalf

Important

The validation feature emits annotations. It does not run them. A DTO can exist - constructed by its builder or deserialized by Jackson - in a state that violates its own constraints, and nothing will say so until a Validator is invoked.

Two things that look like validation, but are not:

  • Builder.build() enforces only that required properties were set, throwing NullPointerException. Pattern, size and range checks are not consulted.
  • Jackson deserialization binds whatever the JSON contains. A missing required property arrives as null; a string that does not match its @Pattern is bound unchanged. See Jackson.

So validating is the consumer's job:

Customer customer = objectMapper.readValue(json, Customer.class);

Set<ConstraintViolation<Customer>> violations = validator.validate(customer);

The exception is a framework that does it for you at a boundary it controls - and that is a framework feature, not a ModelMaker one. Spring Boot, for example, validates a request body only when the parameter is annotated and an implementation is on the classpath:

@PostMapping("/customers")
public ResponseEntity<Void> create(@Valid @RequestBody Customer customer) { ... }

Anywhere outside such a boundary - a message consumer, a scheduled job, a CLI parsing a file, a plain ObjectMapper.readValue - call the Validator yourself.

Clone this wiki locally