<!-- yavi skill 0.18.19 -- https://yavi.ik.am -->

---
name: yavi
description: Write Java validation with YAVI 0.18, whose schema API (Yavi.schema() with fromMap/apply) reads untyped input such as a Map, a JSON tree or request parameters and creates a typed object, in the style of Zod. Covers the schema style, the classic ValidatorBuilder style, input readers, Validated results and violations, Spring, Jackson, Kotlin and NullAway integration, and the built-in constraints. Use this whenever a task involves YAVI, Yavi.schema(), ValidatorBuilder, ObjectInputValidator, ConstraintViolations, or validating input in Java.
---

# YAVI

YAVI (Yet Another Validation) is a Java validation library. Version 0.18 adds a schema
API that reads untyped input and creates the object, so that an invalid object never
exists. The classic `ValidatorBuilder` API, which checks an object created beforehand,
is still supported and is the right choice only for that case.

```xml
<dependency>
    <groupId>am.ik.yavi</groupId>
    <artifactId>yavi</artifactId>
    <version>0.18.0</version>
</dependency>
```

- Java 21 or later. YAVI is annotated with JSpecify, and the annotations are `provided`:
  nothing extra is needed at run time.
- This skill was built from the 0.18 documentation,
  https://yavi.ik.am/0.18/en/ ; the pages are bundled verbatim under
  `references/`, indexed by `references/contents.md`.
- The browser runtime that the site uses to run the examples is not part of the skill;
  compile the code in a normal Maven or Gradle project.

## Rules

1. Prefer the schema API (`Yavi.schema()` ... `fromMap(f)` or `apply(f)`) whenever the
   input is not the object yet: a `Map`, a JSON document, request parameters, form
   fields, path variables. Use `ValidatorBuilder` only when the object already exists,
   as with Bean Validation.
2. A schema in progress is not a validator. It ends with `fromMap(f)`, which returns an
   `ObjectInputValidator<X>`, or with `apply(f)`, which returns an `ArgumentsNValidator`.
   The builder is immutable, so each call returns a new stage.
3. A property is required unless `nullable()`, `optional()`, `defaultValue(v)` or
   `recover(v)` says otherwise. An absent key and an explicit `null` are violations with
   `object.required` and `object.notNull`; do not add `notNull()` for that, and the
   function given to `fromMap` is never passed a `null` for a required property.
4. Handle a result with an exhaustive `switch` over the sealed `Validated`:
   `case Validated.Valid<X>(X x) -> ...` and
   `case Validated.Invalid<X>(ConstraintViolations violations) -> ...`. `validate` is the
   `safeParse` of a Zod-style API; the name is kept from 0.17 for backward
   compatibility, and there is no `parse` method. Where every handler of an API maps a
   failure the same way, `validated(...)` throws `ConstraintViolationsException` and one
   `@RestControllerAdvice` handles it; a switch in each handler repeats the response
   mapping.
5. Constraints are methods of the constraint object of the property type. A constraint
   of another type does not compile, so a guess surfaces at build time; check
   `references/built-in-constraints.md` before using a name, and do not invent one.
   `email()` and the other form constraints accept the empty string unless `notBlank()`
   or `notEmpty()` is added.
6. YAVI depends on neither Jackson nor Spring. A JSON tree is read through an
   `InputReader` written once per tree model (`references/integrations-jackson.md`); the
   Spring, Kotlin and NullAway pages are adapters and checks on top of the library.
7. In Kotlin, `am.ik.yavi.builder._enum<T>` and `_object<T>` are reified extensions that
   remove the `Class` argument. A schema that ends with `apply` takes a method reference
   (`apply(::Account)`), not a lambda.
8. The classic API (`ValidatorBuilder`) treats a `null` property as valid unless a
   constraint rejects it, and `validate` on it returns `ConstraintViolations` rather
   than a `Validated`. Do not mix the two models in one validation path.
9. Call `rejectingUnknownProperties()` on the body and the query of an API, so a typo in
   a key is a violation instead of being silently ignored. `readingParameters()` is
   written after it. A form with a checkbox is the exception (Thymeleaf adds
   `_subscribed`).
10. A path variable is text. Take it as a `String` and validate it with the domain's own
    validator rather than a Spring type conversion, so an invalid `{id}` produces the
    same violation shape as a malformed body.
11. A schema that ends in `fromMapReversible` writes the object back as the map of an SQL
    statement; see "A JSON API and an SQL statement". A value has a text form and a Java
    form, so the map validator reads the text and a validator that ends in `apply(f)`
    reads the Java value. Share the single-value validators, keep the two endings, and do
    not convert a value you already hold to text only to reuse the text validator.

## Quickstart

The documentation page below is bundled as it is; it compiles as written, and its
remaining examples run in the site's browser runtime.

## Getting Started

Welcome to YAVI. This page adds the dependency, writes the first schema and validates an input.

> This content is derived from https://hibernate.org/validator/documentation/getting-started/

### Prerequisites

* Java 21 or later. YAVI 0.18 is compiled for Java 21.
* Apache Maven, or an equivalent Gradle setup.

### Project setup

Add YAVI to `pom.xml`:

```xml
<dependency>
    <groupId>am.ik.yavi</groupId>
    <artifactId>yavi</artifactId>
    <version>0.18.0</version>
</dependency>
```

### Choosing a style

YAVI validates in two styles. Choose by what is available when validation starts:

| You have | You want | Use |
| --- | --- | --- |
| Input that is not an object yet: a `Map`, a parsed JSON document, request parameters | To validate it and create the object, so that an invalid object never exists | `Yavi.schema()` with `fromMap(f)` |
| An object that is already created, as with Bean Validation | To check the object and get its violations | `ValidatorBuilder` |

The rest of this page describes the first style. The classic style is shown at the end.

### Defining a schema

`Yavi.schema()` describes the properties of the input. Each property method gives the type, the name and the constraints, and `fromMap` ends the schema with a validator that reads those properties from a `Map<String, Object>` and calls a constructor.

```java
package com.example;

import am.ik.yavi.input.ObjectInputValidator;
import am.ik.yavi.validator.Yavi;

public record Car(String manufacturer, String licensePlate, Integer seatCount) {
    public static final ObjectInputValidator<Car> validator = Yavi.schema()
            ._string("manufacturer")
            ._string("licensePlate", c -> c.greaterThanOrEqual(2).lessThanOrEqual(14))
            ._integer("seatCount", c -> c.greaterThanOrEqual(2))
            .fromMap(Car::new);
}
```

The schema states that:

* `manufacturer` must be a string,
* `licensePlate` must be a string of 2 to 14 characters,
* `seatCount` must be an integer of at least 2.

A property is required. An absent key is reported with `object.required`, and `null` with `object.notNull`, so no `notNull()` is needed and `Car::new` is never given `null`. A property that may be `null` says so with `nullable()` or `optional()`, as described in [Optional and Default Values](references/optional-and-defaults.md).

### Validating input

Give a map to the validator.

> Note: a Zod-style API would call this `parse` or `safeParse`. YAVI keeps `validate` and `validated` for backward compatibility with the 0.17 API. `validate` checks the input and returns a `Validated`, so it plays the role of `safeParse`.

The following program is complete. Press the **Run** button below it to compile and execute the program in your browser; the output appears under the program. The first run downloads the WebAssembly runtime and can take several seconds, so the page may appear idle for a while. Later runs are faster.

The input leaves out `manufacturer`, so the first run reports the missing property. The cell is editable: add `"manufacturer", "yavi"` to the `Map` and press **Run** again. The program then prints the created `Car` (`valid: Car[manufacturer=yavi, ...]`).

```java runnable
import java.util.Map;

import am.ik.yavi.core.ConstraintViolations;
import am.ik.yavi.core.Validated;
import am.ik.yavi.input.ObjectInputValidator;
import am.ik.yavi.validator.Yavi;

public class Main {

    record Car(String manufacturer, String licensePlate, Integer seatCount) {
    }

    static final ObjectInputValidator<Car> validator = Yavi.schema()
            ._string("manufacturer")
            ._string("licensePlate", c -> c.greaterThanOrEqual(2).lessThanOrEqual(14))
            ._integer("seatCount", c -> c.greaterThanOrEqual(2))
            .fromMap(Car::new);

    public static void main(String[] args) {
        switch (validator.validate(Map.of("licensePlate", "DD-AB-123", "seatCount", 4))) {
            case Validated.Valid<Car>(Car car) -> System.out.println("valid: " + car);
            case Validated.Invalid<Car>(ConstraintViolations violations) -> {
                System.out.println("invalid");
                System.out.println(violations.size());
                System.out.println(violations.get(0).message());
            }
        }
    }
}
```
<!-- run: expected output
invalid
1
"manufacturer" is required
-->

A value that does not represent the type of its property is reported with `object.type`, for example `"seatCount" must be of type integer` for the string `"four"`. No exception is thrown for a malformed input.

### Handling the result

`validate` returns a `Validated<Car>`, which holds either the `Car` or the `ConstraintViolations`. Every violation is accumulated, so an invalid input reports every failed rule at once. `Validated` is a sealed interface, so an exhaustive `switch` with record deconstruction handles both cases and the compiler checks that neither is forgotten:

```java
switch (Car.validator.validate(map)) {
    case Validated.Valid<Car>(Car car) -> save(car);
    case Validated.Invalid<Car>(ConstraintViolations violations) ->
        violations.forEach(violation -> report(violation.name(), violation.message()));
}
```

When the caller wants the object or an exception, `validated(map)` returns the `Car` itself and throws a `ConstraintViolationsException` if the input is invalid. `violations.messagesByName()` returns the messages grouped by property, and `violations.details()` returns records that a JSON library serializes for an API response. See [Handling Results](references/result-handling.md) and [Violations](references/violations.md).

### The same schema on another input

The schema is not tied to a `Map`. The same validator reads a JSON tree with `readingWith(reader)`, request parameters with `readingParameters()`, and typed arguments with `apply(f)` instead of `fromMap(f)`. See [JSON Trees](references/input-json.md), [Request Parameters and Forms](references/input-parameters.md) and [Typed Arguments](references/input-arguments.md).

### Validating an object that already exists (classic API)

When the object already exists, declare the constraints on its properties with `ValidatorBuilder`. The classic API returns `ConstraintViolations` for an instance:

```java
package com.example;

import am.ik.yavi.builder.ValidatorBuilder;
import am.ik.yavi.core.ConstraintViolations;
import am.ik.yavi.core.Validator;

public class CarValidation {

    record Car(String manufacturer, String licensePlate, Integer seatCount) {
    }

    static final Validator<Car> validator = ValidatorBuilder.<Car>of()
            .constraint(Car::manufacturer, "manufacturer", c -> c.notNull())
            .constraint(Car::licensePlate, "licensePlate", c -> c.notNull().greaterThanOrEqual(2).lessThanOrEqual(14))
            .constraint(Car::seatCount, "seatCount", c -> c.greaterThanOrEqual(2))
            .build();

    public static void main(String[] args) {
        ConstraintViolations violations = validator.validate(new Car(null, "D", 1));
        System.out.println(violations.size()); // 3
        System.out.println(violations.get(0).message()); // "manufacturer" must not be null
    }
}
```

`ValidatorBuilder.constraint` applies the constraints to the value returned by a getter of the `Car` instance. Unlike a schema property, a value that is `null` is valid unless a constraint such as `notNull()` rejects it. See [Object Validation](references/using-yavi.md).

### Next steps

* [Core Concepts](references/concepts.md) explains the pipeline behind these calls.
* [Defining a Schema](references/defining-a-schema.md) lists the property methods and constraints.
* [Optional and Default Values](references/optional-and-defaults.md) covers absent keys, `null` and defaults.
* [Objects and Collections](references/objects-and-collections.md) covers nested objects, lists and maps.

## A complete Spring MVC controller

This is the shape a YAVI application has at a request boundary. The domain class holds
the `ObjectInputValidator` of its own input, in its own file -- a validator belongs to
the domain, not to a controller, and is reused by a job or a test. The controller is
where that validator is bound to request parameters with `readingParameters`, and where
the result reaches the `BindingResult`. The individual pieces are documented under
`references/integrations-spring.md` and `references/input-parameters.md`.

```java
// signup/Signup.java
import am.ik.yavi.input.ObjectInputValidator;
import am.ik.yavi.validator.Yavi;

public record Signup(String name, String email, Integer age) {

    public static final ObjectInputValidator<Signup> SCHEMA = Yavi.schema()
            ._string("name", c -> c.notBlank().lessThanOrEqual(50))
            ._string("email", c -> c.notBlank().email())
            ._integer("age", c -> c.greaterThanOrEqual(18).lessThanOrEqual(120))
            .fromMap(Signup::new);

}
```

```java
// web/SignupController.java
import java.util.Map;

import am.ik.yavi.core.ConstraintViolations;
import am.ik.yavi.core.StringCoercion;
import am.ik.yavi.core.Validated;
import am.ik.yavi.core.ValueValidator;
import am.ik.yavi.input.ParameterTree;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.validation.MapBindingResult;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.util.MultiValueMap;

@Controller
class SignupController {

    // Signup is a domain type in its own file, and SignupService is another. The same
    // domain schema serves any request that carries the same input; the coercion of the
    // text of a form is the controller's decision.
    static final ValueValidator<Map<String, ?>, Signup> signupValidator = Signup.SCHEMA
            .readingParameters(StringCoercion.strict().trimming());

    private final SignupService signupService;

    SignupController(SignupService signupService) {
        this.signupService = signupService;
    }

    // Runs before every handler of this controller, so the GET request renders the
    // empty form and a rejected POST renders the values that were sent.
    @ModelAttribute
    void signupForm(@RequestParam MultiValueMap<String, String> params, Model model) {
        Map<String, Object> form = ParameterTree.of(params).toParameters(signupValidator.description());
        model.addAllAttributes(new MapBindingResult(form, "signupForm").getModel());
    }

    @GetMapping("/signup")
    String form() {
        return "signup";
    }

    @PostMapping("/signup")
    String signup(@RequestParam MultiValueMap<String, String> params, BindingResult result) {
        return switch (signupValidator.validate(params)) {
            case Validated.Valid<Signup>(Signup signup) -> {
                this.signupService.register(signup);
                yield "redirect:/";
            }
            case Validated.Invalid<Signup>(ConstraintViolations violations) -> {
                violations.apply(result::rejectValue);
                yield "signup";
            }
        };
    }

}
```

```html
<form method="post" th:action="@{/signup}" th:object="${signupForm}">
    <input type="text" th:field="*{name}">
    <span th:if="${#fields.hasErrors('name')}" th:errors="*{name}"></span>
    <input type="text" th:field="*{email}">
    <span th:if="${#fields.hasErrors('email')}" th:errors="*{email}"></span>
    <input type="text" th:field="*{age}">
    <span th:if="${#fields.hasErrors('age')}" th:errors="*{age}"></span>
    <button type="submit">Sign up</button>
</form>
```

- The `@ModelAttribute` method is not optional: without a model attribute, a handler
  that takes a `BindingResult` fails with `An Errors/BindingResult argument is expected
  to be declared immediately after the model attribute`, because Spring MVC creates a
  `BindingResult` only for a form object that it binds.
- Take the parameters as a `MultiValueMap`; a `Map<String, String>` drops all but the
  first value of a key.
- The code of a field error is the message key (`charSequence.email`, `object.type`), so
  a `MessageSource` replaces the message. See `references/messages.md`.
- Thymeleaf adds a hidden `_subscribed` field to a checkbox. No property is defined for
  that key, so a form with a checkbox cannot use `rejectingUnknownProperties()`.

### One controller per form, or the model setup inside the handler

A `@ModelAttribute` method runs before every handler of its controller, and a
`BindingResult` argument resolves to the last model attribute added -- not to the form the
handler validates. With two forms in one controller, every handler receives the
`BindingResult` of whichever form was added last, and no error is raised (verified on
Spring Framework 7); `@ModelAttribute("signupForm") BindingResult` does not select one
either, because the model attribute is the form map, not the `BindingResult`. Keep one
form per controller, or do what the `@ModelAttribute` method does inside each handler:
build the `MapBindingResult` from the parameters, add `getModel()` to the `Model`, and
take no `BindingResult` argument. Nothing is added before the handler runs then, so one
controller can serve several forms (verified).

```java
@PostMapping("/signup")
String signup(@RequestParam MultiValueMap<String, String> params, Model model) {
    MapBindingResult result = new MapBindingResult(
            ParameterTree.of(params).toParameters(signupValidator.description()), "signupForm");
    return switch (signupValidator.validate(params)) {
        case Validated.Valid<Signup>(Signup signup) -> {
            this.signupService.register(signup);
            yield "redirect:/";
        }
        case Validated.Invalid<Signup>(ConstraintViolations violations) -> {
            violations.apply(result::rejectValue);
            model.addAllAttributes(result.getModel());
            yield "signup";
        }
    };
}
```

A GET handler adds the model of the empty form the same way:
`model.addAllAttributes(new MapBindingResult(Map.of(), "signupForm").getModel())`.

## Where validation belongs

Validation is a boundary operation: it turns untyped input -- a JSON body, request
parameters, a path variable, a form, a row -- into a domain object, and every input of an
API is untrusted. The handler or the reader that receives the request runs the contract;
the service and the repository take the typed value and do not check it again. A value
the application generated itself (an identifier, a timestamp) already has its type, so
checking it adds nothing.

At an API boundary the contract is also the error contract: reject unknown keys (rule 9),
validate a path variable with the domain's validator (rule 10), and map
`ConstraintViolationsException` once (rule 4).

## Reusable single-value validators

A field that appears in several contracts is written once as a single-value validator and
composed into each schema:

```java
public static final ReversibleValueValidator<String, String> AUTHOR = Yavi._string("author",
        c -> c.notBlank().lessThanOrEqual(50));

// read from a map, a form or a row
Yavi.schema()._string(AUTHOR)._string(CONTENT).fromMap(...)

// read a Java value the caller already holds
Yavi.schema()._string(AUTHOR)._string(CONTENT).apply(...)
```

- `named("x")` uses a defined validator under another key and `prefixed(...)` places it
  under a collection element; the constraint is not copied.
- `map(f, g)` gives a value its domain type and keeps the text form for writing back; a
  reversible schema built from it writes the object as the parameters of a statement.
- Share the single-value validators, not the schema endings: the map validator reads the
  text form and the `apply` validator reads the Java value. Do not convert a value you
  already hold to text only to reuse the map validator.
- Reusing a validator keeps the name and the message of the field across the contracts.

## A JSON API and an SQL statement

The same schema carries a value from a JSON request, a row and a statement. The property
name is the named parameter of the statement and the alias of the column; a column whose
name differs (`created_at` for `createdAt`) is selected with an alias, not mapped by hand.

```java
this.jdbcClient.sql("""
        INSERT INTO comments (id, author, content, created_at)
        VALUES (:id, :author, :content, :createdAt)
        """).params(Comment.SCHEMA.toMap(comment)).update();

List<Comment> comments = this.jdbcClient.sql("""
        SELECT id, author, content, created_at AS "createdAt" FROM comments
        """).query().listOfRows().stream().map(Comment.SCHEMA::validated).toList();
```

`toMap` writes the text form of a value whose reversible validator maps it (a `UUID`, an
`Instant`), and an entry with `null` for an absent nullable or optional property, because
a named parameter needs its key. A nested map cannot be bound to a statement: read the
columns with `_embedded`, or flatten them.

For a value the application already holds, the schema ends in `apply(f)` and takes the
Java value (`Arguments4Validator<UUID, String, String, Instant, Comment>`); the map
validator for the same value reads the text form:

```java
public static final ReversibleValueValidator<String, UUID> ID = Yavi._string("id",
        c -> c.notBlank().uuid()).map(UUID::fromString, UUID::toString);
```

To read a body without a record in between, build `Arguments2` with
`fromMap(Arguments2::new)` and call `args.map((first, second) -> ...)`.

At the request boundary, call `validated(...)` and handle the exception once, so the
violations of every endpoint have one shape:

```java
@ExceptionHandler(ConstraintViolationsException.class)
ResponseEntity<ApiError> violations(ConstraintViolationsException exception) {
    ConstraintViolations violations = exception.violations();
    // ...
}
```

## Where to look

| Task | Page |
| --- | --- |
| A schema of a Map or a JSON object | `references/defining-a-schema.md`, `references/input-maps.md` |
| Optional, nullable or default property | `references/optional-and-defaults.md` |
| Nested objects, lists and maps | `references/objects-and-collections.md` |
| A value that is one of several shapes | `references/unions.md` |
| Rules across properties | `references/cross-field-rules.md` |
| A constructor that must not receive raw input | `references/value-objects.md` |
| A JSON tree without copying it | `references/input-json.md` |
| Request parameters or a form | `references/input-parameters.md` |
| The result, the violations, the response | `references/result-handling.md`, `references/violations.md`, `references/messages.md` |
| Writing the validated object back | `references/writing-back.md` |
| Where to validate | this page, "Where validation belongs" |
| Reusing a field validator across schemas | this page, "Reusable single-value validators" |
| A JSON API and SQL parameters | this page, "A JSON API and an SQL statement" |
| Spring, Jackson, Kotlin, NullAway | `references/integrations-*.md` |
| The classic `ValidatorBuilder` API | `references/using-yavi.md` and the rest of the Classic Validators section |
| Every constraint | `references/built-in-constraints.md` |
| Coming from Bean Validation or Zod | `references/coming-from-bean-validation.md`, `references/coming-from-zod.md` |

## The bundled documentation

Every page of the site, at the path it has there.

| Section | Page | Reference |
| --- | --- | --- |
| Getting Started | Overview | `references/index.md` |
| Getting Started | Introduction | `references/introduction.md` |
| Getting Started | Getting Started | `references/getting-started.md` |
| Getting Started | Core Concepts | `references/concepts.md` |
| Getting Started | Agent Skill | `references/agent-skill.md` |
| Schemas | Defining a Schema | `references/defining-a-schema.md` |
| Schemas | Optional and Default Values | `references/optional-and-defaults.md` |
| Schemas | Value Objects and Transforms | `references/value-objects.md` |
| Schemas | Objects and Collections | `references/objects-and-collections.md` |
| Schemas | Unions | `references/unions.md` |
| Schemas | Cross-Field Rules | `references/cross-field-rules.md` |
| Schemas | Describing a Schema | `references/describing-a-schema.md` |
| Inputs | Maps and Untyped Values | `references/input-maps.md` |
| Inputs | JSON Trees | `references/input-json.md` |
| Inputs | Request Parameters and Forms | `references/input-parameters.md` |
| Inputs | Typed Arguments | `references/input-arguments.md` |
| Results | Handling Results | `references/result-handling.md` |
| Results | Violations | `references/violations.md` |
| Results | Messages and Localization | `references/messages.md` |
| Codecs | Writing an Object Back | `references/writing-back.md` |
| Integrations | Integration Overview | `references/integrations.md` |
| Integrations | Spring | `references/integrations-spring.md` |
| Integrations | Jackson | `references/integrations-jackson.md` |
| Integrations | Kotlin | `references/integrations-kotlin.md` |
| Integrations | NullAway | `references/integrations-nullaway.md` |
| Classic Validators | Object Validation | `references/using-yavi.md` |
| Classic Validators | Custom Constraints | `references/custom-constraints.md` |
| Classic Validators | Argument Validation | `references/validating-arguments.md` |
| Classic Validators | Combining Validators | `references/combining-validators.md` |
| Classic Validators | Combining Results | `references/combining-validation-results.md` |
| Classic Validators | Annotation Processor | `references/annotation-processor.md` |
| Reference | Built-in Constraints | `references/built-in-constraints.md` |
| Reference | Migration from 0.17 | `references/migration-0.17-to-0.18.md` |
| Reference | Comparison with Zod | `references/coming-from-zod.md` |
| Reference | Comparison with Bean Validation | `references/coming-from-bean-validation.md` |


---

# FILE: references/agent-skill.md

# Agent Skill

An AI coding agent that knows Bean Validation still writes wrong YAVI code: it validates an object after creating it, reaches for a constraint the type does not have, and handles a result with `getErrors()` that no longer exists. The **agent skill** closes that gap. It is this documentation packaged as a Claude skill: a `SKILL.md` carrying the working rules, plus every page here as a bundled reference, generated on each deploy from the same Markdown, so it cannot drift from what you are reading.

## Install into Claude Code

The skill is published as a plugin. Add the marketplace and install it:

```bash
claude plugin marketplace add https://yavi.ik.am/skill/marketplace.json
claude plugin install yavi@yavi
```

The same two steps work inside a session as `/plugin marketplace add ...` and `/plugin install yavi@yavi`. Add `--scope project` to the first command to declare the marketplace in the repository instead of your user settings, so everyone working on the checkout gets the same offer.

Nothing else is needed: the agent consults the skill by itself when a task involves YAVI -- a `Yavi.schema()` chain, a `ValidatorBuilder`, or a request that names the library.

```bash
claude plugin update yavi@yavi     # take a newer version
claude plugin uninstall yavi@yavi  # remove it
claude plugin list                 # what is installed
```

Claude Code re-reads the marketplace file from that URL, so a new version becomes available without you changing anything -- see [Staying current](#staying-current) for how the version moves.

## Install without the plugin system

A skill is a directory, and Claude Code reads every skill under `~/.claude/skills` (yours) or `.claude/skills` (the repository's). If you would rather drop it in than register a marketplace:

```bash
mkdir -p ~/.claude/skills && \
  curl -sSL https://yavi.ik.am/skill/yavi-skill.tar.gz | tar xz -C ~/.claude/skills
```

Swap the target for `.claude/skills` to install it into the project instead. Either way you end up with `skills/yavi/SKILL.md` and `skills/yavi/references/`; `/skills` lists what is loaded, and removing the `yavi` directory uninstalls it. Nothing updates it for you, so this is the path where you check the version yourself.

## Other agents and hosts

| File | Use |
| --- | --- |
| [marketplace.json](https://yavi.ik.am/skill/marketplace.json) | the plugin marketplace, added by URL as above |
| [yavi-plugin.zip](https://yavi.ik.am/skill/yavi-plugin.zip) | the plugin itself, if you install plugins some other way |
| [yavi-skill.tar.gz](https://yavi.ik.am/skill/yavi-skill.tar.gz) | the bare skill directory, for a `skills` folder |
| [yavi.skill](https://yavi.ik.am/skill/yavi.skill) | the same tree as a zip, to upload where a skill is uploaded rather than unpacked |
| [SKILL.md](https://yavi.ik.am/skill/yavi/SKILL.md) | the skill body alone, readable in place |
| [yavi-full.md](https://yavi.ik.am/skill/yavi-full.md) | documentation and skill as ONE Markdown file, for a tool that has no skill loader |

## Staying current

The skill is versioned `<documented version>.<number of commits that can change it>`, so it moves only when a page or the generator does. A rebuild that produces the same bytes keeps the published version, so an unchanged documentation does not ask every installation to re-download itself. As a plugin, `claude plugin update yavi@yavi` takes the new one. Installed by hand, compare your copy against the published version and reinstall when they differ:

```bash
head -3 ~/.claude/skills/yavi/SKILL.md            # version: 0.18.42
curl -sSL https://yavi.ik.am/skill/VERSION
```

Reinstalling is the same command as installing -- it overwrites in place. [version.json](https://yavi.ik.am/skill/version.json) carries the same version plus the commit it was built from and a hash of the content, if you would rather check it from a script.

## What is inside

`SKILL.md` states the rules an agent with Bean Validation or Zod habits gets wrong: which style to choose, that a schema is not a validator until `fromMap` or `apply` ends it, that a required property is not written as `notNull()`, how `Validated` is handled with an exhaustive `switch`, and where the Kotlin helpers differ. It inlines [Getting Started](getting-started.md) as the quickstart, and carries a complete Spring MVC controller -- schema, `@ModelAttribute`, `BindingResult` and the Thymeleaf form -- for the shape a request boundary has. Under `references/`:

- `contents.md`, every page of this documentation by title.
- every page of this documentation, verbatim, at the same relative paths -- so a detail the skill needs is a file read away, with no network.
- the pages of the site's runnable examples as they are; the expected output is kept in the hidden `run:` comment, and the `Run` button is simply absent.

The skill mirrors one documentation version, the newest one, in English.


---

# FILE: references/annotation-processor.md

# Annotation Processor

The annotation processor generates a meta class for the members of a type annotated with `am.ik.yavi.meta.ConstraintTarget` or `am.ik.yavi.meta.ConstraintArguments`. A meta constant names a property and reads it with a `Function`, so a validator does not use a string literal for the name.

## Enabling the annotation processor

The processor is packaged in the `yavi` artifact. With JDK 21 and earlier, `mvn clean compile` discovers it on the compile classpath. JDK 23 and later do not run annotation processors found on the classpath implicitly, so declare the processor explicitly:

```xml
<plugin>
    <groupId>org.apache.maven.plugins</groupId>
    <artifactId>maven-compiler-plugin</artifactId>
    <configuration>
        <annotationProcessorPaths>
            <path>
                <groupId>am.ik.yavi</groupId>
                <artifactId>yavi</artifactId>
                <version>0.18.0</version>
            </path>
        </annotationProcessorPaths>
    </configuration>
</plugin>
```

`@ConstraintTarget` and `@ConstraintArguments` have source retention, so they are not present at runtime.

## Annotating a target

`@ConstraintTarget` is written on a getter or on a constructor parameter. The processor generates `_UserFormMeta` for the type `UserForm`, with one constant per annotated member.

```java
public class UserForm {

    private String name;

    private Integer age;

    @ConstraintTarget
    public String getName() {
        return name;
    }

    @ConstraintTarget
    public Integer getAge() {
        return age;
    }

}
```

The constants are passed to `ValidatorBuilder#constraint`:

```java
Validator<UserForm> validator = ValidatorBuilder.<UserForm>of()
        .constraint(_UserFormMeta.NAME, c -> c.notBlank())
        .constraint(_UserFormMeta.AGE, c -> c.greaterThan(0))
        .build();
```

On a constructor parameter, `@ConstraintTarget(getter = false)` uses a method with the name of the parameter, which suits a record. `@ConstraintTarget(field = true)` reads the field directly; the field must be accessible from the generated class, which is in the same package.

```java
public record UserForm(@ConstraintTarget(getter = false) String name,
        @ConstraintTarget(getter = false) Integer age) {
}
```

## Annotating arguments

`@ConstraintArguments` is written on a constructor or on a method. A constructor of `User` generates `_UserArgumentsMeta`; a method `createUser` of `UserService` generates `_UserServiceCreateUserArgumentsMeta`, in which the receiver is the first argument.

```java
public class User {

    @ConstraintArguments
    public User(String name, String email, int age) {
        // ...
    }

}
```

The constants are passed to the builder of `ArgumentsValidatorBuilder#of`:

```java
Arguments3Validator<String, String, Integer, User> validator = ArgumentsValidatorBuilder
        .of(User::new)
        .builder(b -> b.constraint(_UserArgumentsMeta.NAME, c -> c.notBlank())
                .constraint(_UserArgumentsMeta.EMAIL, c -> c.notBlank().email())
                .constraint(_UserArgumentsMeta.AGE, c -> c.greaterThan(0)))
        .build();
```

For a method, the receiver is validated as the first argument:

```java
Arguments4Validator<UserService, String, String, Integer, User> validator = ArgumentsValidatorBuilder
        .of(UserService::createUser)
        .builder(b -> b.constraint(_UserServiceCreateUserArgumentsMeta.USERSERVICE, c -> c.notNull())
                .constraint(_UserServiceCreateUserArgumentsMeta.NAME, c -> c.notBlank())
                .constraint(_UserServiceCreateUserArgumentsMeta.EMAIL, c -> c.notBlank().email())
                .constraint(_UserServiceCreateUserArgumentsMeta.AGE, c -> c.greaterThan(0)))
        .build();
```

## Supported meta types

The processor generates a meta for the declared type of the annotated member. The following meta types are available in `am.ik.yavi.meta`:

* `StringConstraintMeta`
* `BooleanConstraintMeta`, `CharacterConstraintMeta`, `ByteConstraintMeta`, `ShortConstraintMeta`, `IntegerConstraintMeta`, `LongConstraintMeta`, `FloatConstraintMeta`, `DoubleConstraintMeta`
* `BigIntegerConstraintMeta`, `BigDecimalConstraintMeta`
* `ObjectConstraintMeta`
* `LocalDateConstraintMeta`, `LocalTimeConstraintMeta`, `LocalDateTimeConstraintMeta`, `OffsetDateTimeConstraintMeta`, `InstantConstraintMeta`, `YearConstraintMeta`, `YearMonthConstraintMeta`, `ZonedDateTimeConstraintMeta`

An enum target uses `ObjectConstraintMeta`.

## Changes in 0.18

* The generated code is annotated with JSpecify (`@org.jspecify.annotations.Nullable`), as the API is. Add `org.jspecify:jspecify` to the dependencies if the generated sources are compiled against the annotation.
* `Arguments1` to `Arguments16` are records, and the generated meta of a method refers to the container of the receiver, as shown above.
* Use the YAVI version of the project in `annotationProcessorPaths`; the example follows the version of this documentation.


---

# FILE: references/built-in-constraints.md

# Built-in Constraints

YAVI provides built-in constraints for each supported type. The same constraint object is used by the schema style and by the classic style, so each constraint is documented once on this page.

The following program applies `email()`, `ip()` and `multipleOf(3)` and prints the violation for each invalid value.

```java runnable
import am.ik.yavi.core.ConstraintViolations;
import am.ik.yavi.validator.Yavi;

public class Main {

    public static void main(String[] args) {
        ConstraintViolations violations = new ConstraintViolations();
        violations.addAll(Yavi._string("email", c -> c.email()).validate("not-an-email").errors());
        violations.addAll(Yavi._string("host", c -> c.ip()).validate("999.0.0.1").errors());
        violations.addAll(Yavi._integer("quantity", c -> c.multipleOf(3)).validate(10).errors());
        for (var violation : violations) {
            System.out.println(violation.name() + ": " + violation.message());
        }
    }

}
```
<!-- run: expected output
email: "email" must be a valid email address
host: "host" must be a valid IP address
quantity: "quantity" must be a multiple of 3
-->

```java
import am.ik.yavi.builder.ValidatorBuilder;
import am.ik.yavi.core.Validator;
import am.ik.yavi.validator.Yavi;

// Schema style: the validator of a single value
var emailValidator = Yavi._string("email", c -> c.notBlank().email());

// Classic style: a property of an object
record Signup(String email) {}

Validator<Signup> signupValidator = ValidatorBuilder.<Signup>of()
        ._string(Signup::email, "email", c -> c.notBlank().email())
        .build();
```

The lambdas are identical. In the schema style, a property is also written with `Yavi.schema()._string("email", c -> ...)`; in the classic style, the typed method `_string` selects the type of the property and avoids an ambiguous inference, and `constraint` is the untyped alternative.

## Null values and required values

The schema style and the classic style differ in what `null` means.

* A property of `Yavi.schema()` and a validator of a single value built with `Yavi._string(...)` reject `null` by default with `object.notNull`. A value that may be `null` declares it with `nullable()` (or `optional()`, `defaultValue(...)`, `recover(...)`); see [Optional and Default Values](optional-and-defaults.md). `isNull()` is usable only after `nullable()`.
* A property of a `ValidatorBuilder` validator is valid when it is `null`, and every check is skipped, unless a constraint rejects `null`. `notNull()`, `notBlank()` and `notEmpty()` reject `null`; the other constraints on this page do not.
* An empty string is valid for every format of a string, whatever the style. A format tells what a given text looks like, not that a text is given. Add `notEmpty()` or `notBlank()` to require it.

The message key and the `params` names of each constraint are listed with it. `params` of a violation holds the arguments by name and does not include the name of the value or the violated value; the positional arguments remain available from `ConstraintViolation#args()`. See [Violations](violations.md#violationdetail).

## String and CharSequence

Use `_string` for a `String`; the classic style also has `_charSequence` for a `CharSequence`. The constraints are in `am.ik.yavi.constraint.CharSequenceConstraint`.

| Constraint | Method | Accepted values | Message key | `params` |
| --- | --- | --- | --- | --- |
| Not null | `notNull()` | any non-null value | `object.notNull` | - |
| Null | `isNull()` | only `null` | `object.isNull` | - |
| Not empty | `notEmpty()` | non-null, not empty | `container.notEmpty` | - |
| Not blank | `notBlank()` | non-null, not only white space | `charSequence.notBlank` | - |
| Fixed size | `fixedSize(int)` | the given number of characters | `container.fixedSize` | `size`, `actualSize` |
| Size greater than | `greaterThan(int)` | more than the given number | `container.greaterThan` | `min`, `actualSize` |
| Size greater than or equal | `greaterThanOrEqual(int)` | at least the given number | `container.greaterThanOrEqual` | `min`, `actualSize` |
| Size less than | `lessThan(int)` | fewer than the given number | `container.lessThan` | `max`, `actualSize` |
| Size less than or equal | `lessThanOrEqual(int)` | at most the given number | `container.lessThanOrEqual` | `max`, `actualSize` |
| Contains | `contains(CharSequence)` | text containing the sequence | `charSequence.contains` | `substring` |
| Starts with | `startsWith(CharSequence)` | text starting with the prefix | `charSequence.startsWith` | `prefix` |
| Ends with | `endsWith(CharSequence)` | text ending with the suffix | `charSequence.endsWith` | `suffix` |
| Pattern | `pattern(String)`, `pattern(Pattern)`, `pattern(Supplier<Pattern>)` | text matching the regular expression | `charSequence.pattern` | `pattern` |
| Email | `email()` | an email address | `charSequence.email` | - |
| UUID | `uuid()` | 8-4-4-4-12 hexadecimal; version and variant are not checked | `charSequence.uuid` | - |
| ULID | `ulid()` | 26 characters of Crockford Base32, first `0`-`7`, upper or lower case | `charSequence.ulid` | - |
| IP address | `ip()` | an IPv4 or IPv6 address | `charSequence.ip` | - |
| IPv4 | `ipv4()` | an IPv4 address | `charSequence.ipv4` | - |
| IPv6 | `ipv6()` | an IPv6 address, including a zone id and a prefix length | `charSequence.ipv6` | - |
| URI | `uri()` | an absolute URI with a scheme of any kind (`mailto:`, `urn:`, `s3://`); a character outside US-ASCII is rejected | `charSequence.uri` | - |
| URL | `url()` | a URL that `java.net.URI` parses | `charSequence.url` | - |
| URL with restrictions | `url(url -> url.protocol(...).host(...).port(...).build())` | a valid URL whose protocol, host and port are in the given sets | `charSequence.url`, `charSequence.url.protocol`, `charSequence.url.host`, `charSequence.url.port` | `values` |
| Luhn | `luhn()` | decimal digits that pass the Luhn checksum | `charSequence.luhn` | - |
| Password policy | `password(policy -> ...)` | text that meets the policies | `password.required`, `password.optional` | `policy` / `min`, `policies` |
| Byte representation | `isByte()` | text that parses as a `Byte` | `charSequence.byte` | - |
| Short representation | `isShort()` | text that parses as a `Short` | `charSequence.short` | - |
| Integer representation | `isInteger()` | text that parses as an `Integer` | `charSequence.integer` | - |
| Long representation | `isLong()` | text that parses as a `Long` | `charSequence.long` | - |
| Float representation | `isFloat()` | text that parses as a `Float` | `charSequence.float` | - |
| Double representation | `isDouble()` | text that parses as a `Double` | `charSequence.double` | - |
| BigInteger representation | `isBigInteger()` | text that parses as a `BigInteger` | `charSequence.biginteger` | - |
| BigDecimal representation | `isBigDecimal()` | text that parses as a `BigDecimal` | `charSequence.bigdecimal` | - |
| Local date | `isoLocalDate()`, `localDate(String pattern)` | a date in the pattern, resolved with `ResolverStyle.STRICT` | `charSequence.localdate` | `pattern` |

`ip()`, `uri()` and `ulid()` are new in 0.18. `url(builder)` restricts the parsed URL: `protocol` accepts protocol names, `host` accepts host names compared case-insensitively as written, and `port` accepts port numbers; a URL without an explicit port is matched against the default port of its protocol.

```java
var proxyValidator = Yavi._string("proxy", c -> c.notBlank().ip());
proxyValidator.validate("");                 // "proxy" must not be blank
proxyValidator.validate("192.0.2.1");        // Valid
proxyValidator.validate("2001:db8::1");      // Valid
proxyValidator.validate("example.com");      // Invalid (charSequence.ip)

var homepageValidator = Yavi._string("homepage", c -> c.uri());
homepageValidator.validate("mailto:a@example.com"); // Valid
homepageValidator.validate("/relative/path");       // Invalid
```

`pattern(Supplier<Pattern>)` calls the supplier for every validation, for regular expressions that are built at validation time.

Built-in password policies are `UPPERCASE`, `LOWERCASE`, `ALPHABETS`, `NUMBERS` and `SYMBOLS` in `am.ik.yavi.constraint.password.PasswordPolicy`. A policy is required with `required(...)` or made one of a minimum count with `optional(int, ...)`; `uppercase(2)` requires two upper case characters. A custom `PasswordPolicy` can be passed in the same way.

## Character counting and byte size

The size constraints of a character sequence count Unicode code points after normalization and after the ignored variation selectors are removed. The default normalizer is `Normalizer.Form.NFC`, so `モジ` written as `モシ` plus a voiced sound mark counts as two characters instead of three. The constraints that inspect the text itself (`contains`, `startsWith`, `endsWith`, `pattern`, the formats and `codePoints`) do not normalize the value.

| Constraint | Method | Effect | Message key | `params` |
| --- | --- | --- | --- | --- |
| Normalizer | `normalizer(Normalizer.Form)`, `normalizer(null)` | sets or disables the normalization applied before the size is measured | - | - |
| Emoji | `emoji()` | counts emoji sequences as one character, using extended grapheme clusters; it is off by default | - | - |
| Variant selectors | `variant(opts -> opts.ivs(...).svs(...).fvs(...))` | removes the selected variation selectors before the size is measured | - | - |
| Code points | `codePoints(...).asWhiteList()`, `.asBlackList()` | allows or forbids the given code points | `codePoints.asWhiteList`, `codePoints.asBlackList` | `notAllowed` |
| Byte size | `asByteArray()`, `asByteArray(Charset)` followed by `fixedSize`, `greaterThan`, `greaterThanOrEqual`, `lessThan`, `lessThanOrEqual` | measures the encoded byte length | `byteSize.fixedSize`, `byteSize.greaterThan`, `byteSize.greaterThanOrEqual`, `byteSize.lessThan`, `byteSize.lessThanOrEqual` | `size`, `actualSize` / `min`, `actualSize` / `max`, `actualSize` |

`emoji()` is not enabled by default because it is expensive. In 0.18 it counts extended grapheme clusters, so `"\r\n"` and a half-width katakana with a voiced sound mark count as one; the `Emoji` class is removed.

`normalizer`, `emoji()` and `variant(...)` are not constraints by themselves: the message of the size constraint applied to their result is reported. Code point sets are represented by `am.ik.yavi.constraint.charsequence.CodePoints`, and built-in sets are available from `AsciiCodePoints` and `UnicodeCodePoints`.

An emoji sequence is counted as one only when `emoji()` is added; otherwise each code point is counted. `asByteArray()` measures the UTF-8 byte length unless a charset is given, for a column whose byte length is limited.

```java
var messageValidator = Yavi._string("text", c -> c.emoji().lessThanOrEqual(3)
        .asByteArray().lessThanOrEqual(16));
messageValidator.validate("I❤️☕️️");        // Valid
messageValidator.validate("❤️❤️❤️️️");     // Invalid (byteSize.lessThanOrEqual)
```

## Integral numbers

The classic style uses `_byte`, `_short`, `_integer`, `_long`, `_character` and `_bigInteger` for the corresponding types; the schema style has `_short`, `_integer`, `_long` and `_bigInteger`. The constraints on `Character` compare the numeric value of the character; the zero value used by `positive` and the other sign constraints is `Character.MIN_VALUE`.

| Constraint | Method | Accepted values | Message key | `params` |
| --- | --- | --- | --- | --- |
| Not null | `notNull()` | any non-null value | `object.notNull` | - |
| Null | `isNull()` | only `null` | `object.isNull` | - |
| Greater than | `greaterThan(V)` | greater than the bound | `numeric.greaterThan` | `min` |
| Greater than or equal | `greaterThanOrEqual(V)` | at least the bound | `numeric.greaterThanOrEqual` | `min` |
| Less than | `lessThan(V)` | less than the bound | `numeric.lessThan` | `max` |
| Less than or equal | `lessThanOrEqual(V)` | at most the bound | `numeric.lessThanOrEqual` | `max` |
| Positive | `positive()` | greater than zero | `numeric.positive` | - |
| Positive or zero | `positiveOrZero()` | zero or greater | `numeric.positiveOrZero` | - |
| Negative | `negative()` | less than zero | `numeric.negative` | - |
| Negative or zero | `negativeOrZero()` | zero or less | `numeric.negativeOrZero` | - |
| Multiple | `multipleOf(V)` | a multiple of the divisor | `numeric.multipleOf` | `divisor` |

`multipleOf` is available for `Byte`, `Short`, `Integer`, `Long`, `BigInteger` and `BigDecimal`; `Character`, `Double` and `Float` do not have it.

```java
var quantityValidator = Yavi._integer("quantity", c -> c.multipleOf(12));
quantityValidator.validate(24);  // Valid
quantityValidator.validate(30);  // Invalid ("quantity" must be a multiple of 12)
```

## BigInteger and BigDecimal

`BigInteger` and `BigDecimal` have the constraints of the integral types, including `multipleOf`. `BigDecimal` additionally has the constraints on the number of digits.

| Constraint | Method | Accepted values | Message key | `params` |
| --- | --- | --- | --- | --- |
| Fraction digits | `fractionDigits(int)` | at most the given number of digits after the decimal point; trailing zeros are not counted | `numeric.fractionDigits` | `max` |
| Integer digits | `integerDigits(int)` | at most the given number of digits before the decimal point; the zero of `0.5` is not counted | `numeric.integerDigits` | `max` |

The comparisons use `BigDecimal#compareTo` and ignore the scale, so `1.0` and `1.00` are the same value and both have no fraction digit. The scale is not changed by the constraint; use `preprocess` or `map` when the produced value must have a fixed scale.

```java
var priceValidator = Yavi._bigDecimal("price", c -> c.fractionDigits(2).integerDigits(6));
priceValidator.validate(new BigDecimal("1.50"));  // Valid (1.5 has one fraction digit)
priceValidator.validate(new BigDecimal("1.505")); // Invalid (numeric.fractionDigits)
```

## Double and Float

`_double` and `_float` have `notNull`, `isNull`, `greaterThan`, `greaterThanOrEqual`, `lessThan`, `lessThanOrEqual`, `positive`, `positiveOrZero`, `negative` and `negativeOrZero`, with the same message keys as the integral types. They do not have `multipleOf`, because the remainder of a binary fraction is not exact. `NaN` satisfies none of the bounds and is rejected by every comparison.

## Temporal

The temporal constraints are available for the following types, with the classic builder shortcuts. The schema style uses the same names as property methods, for example `Yavi.schema()._localDate("date", c -> c.past())`.

| Type | Constraint class | Classic shortcut |
| --- | --- | --- |
| `LocalDate` | `LocalDateConstraint` | `_localDate` |
| `LocalTime` | `LocalTimeConstraint` | `_localTime` |
| `LocalDateTime` | `LocalDateTimeConstraint` | `_localDateTime` |
| `OffsetDateTime` | `OffsetDateTimeConstraint` | `_offsetDateTime` |
| `Instant` | `InstantConstraint` | `_instant` |
| `Year` | `YearConstraint` | `_year` |
| `YearMonth` | `YearMonthConstraint` | `_yearMonth` |
| `ZonedDateTime` | `ZonedDateTimeConstraint` | `_zonedDateTime` |

| Constraint | Method | Accepted values | Message key | `params` |
| --- | --- | --- | --- | --- |
| Past | `past()`, `past(Clock)` | before the current time | `temporal.past` | - |
| Past or present | `pastOrPresent()`, `pastOrPresent(Clock)` | at or before the current time | `temporal.pastOrPresent` | - |
| Future | `future()`, `future(Clock)` | after the current time | `temporal.future` | - |
| Future or present | `futureOrPresent()`, `futureOrPresent(Clock)` | at or after the current time | `temporal.futureOrPresent` | - |
| Before | `before(Supplier<T>)` | before the supplied boundary | `temporal.before` | `other` |
| Before or equal | `beforeOrEqual(Supplier<T>)` | at or before the supplied boundary | `temporal.beforeOrEqual` | `other` |
| After | `after(Supplier<T>)` | after the supplied boundary | `temporal.after` | `other` |
| After or equal | `afterOrEqual(Supplier<T>)` | at or after the supplied boundary | `temporal.afterOrEqual` | `other` |
| Between | `between(Supplier<T>, Supplier<T>)` | strictly between the supplied bounds | `temporal.between` | `rangeFrom`, `rangeTo` |
| Field | `fieldPredicate(TemporalField, LongPredicate)` | a value of the field accepted by the predicate | `temporal.field` | `field` |

`before`, `beforeOrEqual`, `after`, `afterOrEqual` and `between` have an overload with a `boolean memoize` argument. It is `true` by default, so the supplier is called at most once and the same value is used for the comparison and the message. `between` throws `IllegalArgumentException` when `rangeFrom` is after `rangeTo`. The `Clock` overloads exist for deterministic tests and for a time source other than the system default zone.

A `null` value is valid and skips every temporal check.

## Boolean

| Constraint | Method | Accepted values | Message key | `params` |
| --- | --- | --- | --- | --- |
| Not null | `notNull()` | any non-null value | `object.notNull` | - |
| Null | `isNull()` | only `null` | `object.isNull` | - |
| True | `isTrue()` | `true` | `boolean.isTrue` | - |
| False | `isFalse()` | `false` | `boolean.isFalse` | - |

## Collection and array

Use `_collection` for a `Collection` and `_objectArray`, `_booleanArray`, `_byteArray`, `_charArray`, `_shortArray`, `_intArray`, `_longArray`, `_floatArray` or `_doubleArray` for an array. The element or value validation of a list, a map and an array, including `_list`, `_map` and `forEach`, is described in [Objects and Collections](objects-and-collections.md#lists).

| Constraint | Method | Accepted values | Message key | `params` |
| --- | --- | --- | --- | --- |
| Not null | `notNull()` | any non-null value | `object.notNull` | - |
| Null | `isNull()` | only `null` | `object.isNull` | - |
| Not empty | `notEmpty()` | a non-empty collection or array | `container.notEmpty` | - |
| Fixed size | `fixedSize(int)` | the given number of elements | `container.fixedSize` | `size`, `actualSize` |
| Size greater than | `greaterThan(int)` | more than the given number | `container.greaterThan` | `min`, `actualSize` |
| Size greater than or equal | `greaterThanOrEqual(int)` | at least the given number | `container.greaterThanOrEqual` | `min`, `actualSize` |
| Size less than | `lessThan(int)` | fewer than the given number | `container.lessThan` | `max`, `actualSize` |
| Size less than or equal | `lessThanOrEqual(int)` | at most the given number | `container.lessThanOrEqual` | `max`, `actualSize` |
| Contains | `contains(E)` | a collection or array containing the element | `collection.contains`, `array.contains` | `element` |
| Unique | `unique()` | elements without duplicates | `collection.unique` | `duplicates` |
| Unique by key | `unique(Function<? super E, ?>)` | elements whose keys are unique | `collection.uniqueBy` | `duplicates` |
| Contains all | `containsAll(Collection<? extends E>)` | all of the given elements | `collection.containsAll` | `values`, `missing` |

`unique(key)` reports the duplicated keys. A `Set` and a non-`Set` collection have the same semantics for `containsAll`. A `null` array is valid and the checks are skipped, except `notEmpty()`.

```java
var productsValidator = Yavi.schema()._list("products", productValidator, c -> c.unique(Product::id));
// "products" must be unique. [APPLE] is/are duplicated.
```

## Map

Use `_map` for a `Map`.

| Constraint | Method | Accepted values | Message key | `params` |
| --- | --- | --- | --- | --- |
| Not null | `notNull()` | any non-null value | `object.notNull` | - |
| Null | `isNull()` | only `null` | `object.isNull` | - |
| Not empty | `notEmpty()` | a non-empty map | `container.notEmpty` | - |
| Fixed size | `fixedSize(int)` | the given number of entries | `container.fixedSize` | `size`, `actualSize` |
| Size greater than | `greaterThan(int)` | more than the given number | `container.greaterThan` | `min`, `actualSize` |
| Size greater than or equal | `greaterThanOrEqual(int)` | at least the given number | `container.greaterThanOrEqual` | `min`, `actualSize` |
| Size less than | `lessThan(int)` | fewer than the given number | `container.lessThan` | `max`, `actualSize` |
| Size less than or equal | `lessThanOrEqual(int)` | at most the given number | `container.lessThanOrEqual` | `max`, `actualSize` |
| Contains key | `containsKey(K)` | a map containing the key | `map.containsKey` | `key` |
| Contains value | `containsValue(V)` | a map containing the value | `map.containsValue` | `value` |

## Object

Use `_object` for any other object. In the classic style, `constraintOnTarget` applies the constraints to the validated object itself.

| Constraint | Method | Accepted values | Message key | `params` |
| --- | --- | --- | --- | --- |
| Not null | `notNull()` | any non-null value | `object.notNull` | - |
| Null | `isNull()` | only `null` | `object.isNull` | - |
| Equal to | `equalTo(Object)` | a value equal to the given value | `object.equalTo` | `value` |
| One of | `oneOf(Collection)` | one of the given values | `object.oneOf` | `values` |
| Not one of | `notOneOf(Collection)` | none of the given values | `object.notOneOf` | `values` |
| Password policy | `password(policy -> ...)` | a value that meets the policies; a policy can inspect the whole object | `password.required`, `password.optional` | `policy` / `min`, `policies` |

## Enum

Use `_enum` for an enum. The schema style and the classic style both take the enum type.

```java
var statusValidator = Yavi._enum("status", Status.class, c -> c.oneOf(Status.ACTIVE));
statusValidator.validate(Status.ACTIVE);   // Valid
statusValidator.validate(Status.INACTIVE); // Invalid ("status" must be one of the following values: [ACTIVE])
```

| Constraint | Method | Accepted values | Message key | `params` |
| --- | --- | --- | --- | --- |
| Not null | `notNull()` | any non-null value | `object.notNull` | - |
| Null | `isNull()` | only `null` | `object.isNull` | - |
| One of | `oneOf(E...)` | one of the given constants; the list must not be empty | `object.oneOf` | `values` |

A `null` enum value is valid in the classic style unless `notNull()` is added. `EnumValidatorBuilder` and `EnumValidator` validate a single enum value.


---

# FILE: references/combining-validation-results.md

# Combining Results

A validation result can be combined with another one. The combination is applicative: every validation is executed and every violation is accumulated, so a caller sees all failures at once.

## Applicative validation

`Validation<E, T>` is the validation result type. `am.ik.yavi.core.Validated<T>` is a `Validation<ConstraintViolation, T>` that a validator returns.

```java
ApplicativeValidator<Email> emailValidator = validator.applicative();
Validated<Email> validated = emailValidator.validate(email);

if (validated.isValid()) {
    Email value = validated.value();
}
else {
    ConstraintViolations violations = validated.errors();
}
```

In 0.18 `Validation` is an interface and `Validated` is a sealed interface of the records `Validated.Valid` and `Validated.Invalid`, so a result is handled with an exhaustive `switch`:

```java
switch (validated) {
    case Validated.Valid<Email>(Email email) -> send(email);
    case Validated.Invalid<Email>(ConstraintViolations violations) ->
        violations.forEach(violation -> report(violation.name(), violation.message()));
}
```

`validated.value()` throws when the result is invalid and `errors()` throws when it is valid. `orElseThrow` and `throwIfInvalid` raise the exception returned by their function.

```java
Email email = validated.orElseThrow(ConstraintViolationsException::new);
validated.throwIfInvalid(ConstraintViolationsException::new);
```

`fold` creates a value of one type for both outcomes.

```java
HttpStatus status = validated.fold(violations -> HttpStatus.BAD_REQUEST, email -> HttpStatus.OK);
```

## Mapping and inspecting results

`map`, `flatMap`, `mapError`, `mapErrors`, `bimap`, `peek` and `peekErrors` transform a result. In 0.18 `map` and `flatMap` have one type parameter:

```java
Validation<ConstraintViolation, String> mapped = validated.map(Email::value);
Validation<String, Email> mappedErrors = validated.mapError(ConstraintViolation::messageKey);
Validation<String, String> bimapped = validated
        .bimap(violations -> List.of("invalid"), Email::value);
```

`Validated.successWith`, `Validated.failureWith` and `Validated.of` create a result. `Validated.of` converts a `Validation` to a `Validated`; `ConstraintViolations.of` creates the violations of a `failureWith`.

```java
Validated<Email> success = Validated.successWith(new Email("yavi@example.com"));
Validated<Email> failure = Validated.failureWith(violations);
Validated<Email> converted = Validated.of(Validation.success(new Email("yavi@example.com")));
```

A failure can also be created from a message, for example in a `flatFromMap` or `flatApply` function:

```java
record DateRange(LocalDate start, LocalDate end) {

    static Validated<DateRange> of(LocalDate start, LocalDate end) {
        return start.isBefore(end) ? Validated.successWith(new DateRange(start, end))
                : Validated.failureWith(ViolationMessage.of("dateRange.invalid", "start must be before end"));
    }

}
```

Several results can be combined with `Validated.sequence`, `Validated.traverse`, `Validated.traverseIndexed` and `Validated.traverseOptional`.

```java
Validated<List<Email>> emails = Validated.sequence(List.of(emailValidated, anotherEmailValidated));
Validated<List<Email>> traversed = Validated.traverse(inputs, emailValidator::validate);
```

## Combining Validated values

`Validated#combine` returns a `ValidatedCombining2`, and its `apply` returns a `Validated`. Further results are added with `combine` up to 16.

```java
Validated<ContactInfo> contactInfo = emailValidated.combine(phoneNumberValidated)
        .apply(ContactInfo::new);
```

All violations of both results are accumulated and the function is not called when one of them is invalid.

```java
Validated<ContactInfo> invalid = emailValidated.combine(phoneNumberValidated)
        .apply(ContactInfo::new);
// invalid: "email" must not be blank, "email" must be a valid email address,
// "phoneNumber" must match [0-9\-]+
```

`Validations.combine(a, b)` combines the same results and its `apply` returns a `Validation<E, R>`. `Validations.apply(f, a, b)` applies a function directly. In 0.18 these methods return the type they are declared with instead of the type chosen by the caller:

```java
Validation<ConstraintViolation, Address> address = Validations
        .combine(country, street)
        .apply(Address::new);
```

A combination that starts with a `Validation` returns a `Validation`, which is not assignable to a `Validated`. Convert the first result with `Validated.of`:

```java
Validation<ConstraintViolation, Country> country = ...;

Validated<Address> address = Validated.of(country).combine(street).apply(Address::new);
```

## Type changes in 0.18

The 0.18 result types replace the ones of 0.17:

* `Validation` is an interface. A class that extended it implements it, and a `Validated` is a sealed interface.
* `Validated#combine` returns `ValidatedCombiningN`, whose `apply` returns `Validated<R>`.
* `Validation#apply`, `CombiningN#apply` and `Validations.apply` return `Validation<E, R>`.
* `Validation#yieldSuccess` and `Validation#yieldFailure` are removed. Override `map`, `apply` and `combine` instead.
* `Validation#valueNullable()` is deprecated; `value()` returns the null of a success that holds it.
* `Validated#prefixed(int)` replaces `indexed(int)`. `Validation.Success` and `Validation.Failure` are records, and `Validation.Success#value` is no longer a public field.

Code that combines `Validated` results with `combine` and assigns the result to a `Validated` compiles as it is.


---

# FILE: references/combining-validators.md

# Combining Validators

A `ValueValidator<S, T>` validates an input of type `S` and produces a value of type `T`. Argument validators and applicative validators are value validators, so they can be split and combined to validate a larger object.

## Splitting a validator

`ArgumentsValidators.split` combines value validators into an arguments validator. Each validator validates one argument of the function that creates the object.

```java
Arguments3Validator<String, String, Integer, Person> validator = ArgumentsValidators
        .split(nameValidator, emailValidator, ageValidator)
        .apply(Person::new);
```

The same combination can be built from the validators one after another:

```java
Arguments3Validator<String, String, Integer, Person> validator = nameValidator
        .split(emailValidator)
        .split(ageValidator)
        .apply(Person::new);
```

The arguments of `split` are `ValueValidator`s, so an `ApplicativeValidator` can be combined in the same way. A value object is produced when the validators map the values:

```java
Arguments2Validator<Email, PhoneNumber, ContactInfo> validator = ArgumentsValidators
        .split(emailValidator, phoneNumberValidator)
        .apply(ContactInfo::new);

Validated<ContactInfo> validated = validator.validate(new Email("yavi@example.com"),
        new PhoneNumber("090-123-4567"));
```

All violations are accumulated. A combination is validated only when every argument is valid, so the function is not called with an invalid value.

## Chaining and mapping value validators

`andThen(ValueValidator)` applies the value produced by one validator to the next validator.

```java
ValueValidator<String, String> checked = emailValidator
        .andThen(ValueValidator.<Email>passThrough().map(Email::value));
```

`map(Function)` maps the validated value without applying another validator.

```java
ValueValidator<String, String> emailValue = emailValidator.map(Email::value);
```

`andThen(Function)` is removed in 0.18. Use `map(Function)` instead. A validator that knows how to write its value back is built with `map(f, g)`, as described in [Writing an Object Back](writing-back.md).

## Lifting a validator over a collection

`liftList`, `liftSet`, `liftCollection(factory)`, `liftMap` and `liftOptional` apply a validator to every element or value of a container. The violations of an element are located under its index or key.

```java
Arguments1Validator<Iterable<? extends String>, List<Email>> emails = emailValidator.liftList();
Validated<List<Email>> validated = emails.validate(List.of("foo@example.com", "bar@example.com"));

Arguments1Validator<Iterable<? extends String>, Set<Email>> emailSet = emailValidator.liftSet();
Arguments1Validator<Iterable<? extends String>, List<Email>> emailList = emailValidator
        .liftCollection(ArrayList::new);
Arguments1Validator<Optional<? extends String>, Optional<Email>> emailOptional = emailValidator
        .liftOptional();
```

In 0.18 the lifted validator takes a container of a subtype, `Iterable<? extends String>`, so a validator of `Object` lifted to a list validates a `List<String>`.

The violations of a lifted element are located under the index, before the name of the element validator:

```java
Yavi._string("tag", c -> c.notBlank())
        .liftList()
        .validate(List.of("java", ""));
// [1].tag, was tag[1] in 0.17
```

Name the collection rather than the element, with `prefixed(String)`:

```java
Yavi._string(c -> c.notBlank())
        .liftList().prefixed("tag")
        .validate(List.of("java", ""));
// tag[1]

addressValidator.applicative().liftList().prefixed("addresses").validate(addresses);
// addresses[1].street
```

`indexed(int)` is removed. `prefixed(int)` of a `ConstraintViolation` or a `Validated` puts the index before the name:

```java
validated.prefixed(1); // [1].tag
```

`liftList(separator)` also reads a list from one text, such as `1,2,3`.

```java
ValueValidator<Iterable<? extends Integer>, List<Integer>> ids = Yavi._integer(c -> c.positive())
        .liftList(Pattern.compile(","));
```

## Validating the source before the target

`compose` validates a value of another type by converting it first. A validator for a request or a map can therefore create a domain object from values that it reads.

```java
Arguments1Validator<HttpServletRequest, Name> requestNameValidator = nameValidator
        .compose(req -> req.getParameter("name"));
Arguments1Validator<HttpServletRequest, Email> requestEmailValidator = emailValidator
        .compose(req -> req.getParameter("email"));
Arguments1Validator<HttpServletRequest, Integer> requestAgeValidator = ageValidator
        .compose(req -> Integer.valueOf(req.getParameter("age")));

Arguments1Validator<HttpServletRequest, Person> personValidator = ArgumentsValidators
        .combine(requestNameValidator, requestEmailValidator, requestAgeValidator)
        .apply(Person::new);

Validated<Person> validated = personValidator.validate(request);
```

A validator of typed arguments can be converted in the same way; `Arguments.of` builds the arguments the target validator expects.

```java
Arguments1Validator<HttpServletRequest, Person> personValidator = argumentsValidator
        .compose(req -> Arguments.of(req.getParameter("name"), req.getParameter("email"),
                Integer.valueOf(req.getParameter("age"))));
```

The source is validated with the same combination rules: every violation is accumulated and the target is created only when the source is valid.


---

# FILE: references/coming-from-bean-validation.md

# Comparison with Bean Validation

[Bean Validation](https://beanvalidation.org/) declares constraints as annotations on a class and validates an object that already exists. YAVI expresses the same constraints as Java method calls. This page maps the annotations to the constraint API and lists the differences.

## Basic

A Bean Validation form object:

```java
public class UserForm {

  @NotNull
  @Size(min = 1, max = 20)
  private String name;

  @NotNull
  @Size(min = 1, max = 50)
  @Email
  private String email;

  @NotNull
  @Min(0)
  @Max(200)
  private Integer age;

  // omitted setter/getter

}
```

The counterpart validates the object with `ValidatorBuilder`:

```java
Validator<UserForm> validator = ValidatorBuilder.<UserForm>of()
        .constraint(UserForm::getName, "name", c -> c.notNull().greaterThanOrEqual(1).lessThanOrEqual(20))
        .constraint(UserForm::getEmail, "email", c -> c.notNull().greaterThanOrEqual(1).lessThanOrEqual(50).email())
        .constraint(UserForm::getAge, "age", c -> c.notNull().greaterThanOrEqual(0).lessThanOrEqual(200))
        .build();
```

`ValidatorBuilder` is the counterpart of Bean Validation because both validate an object that was created by something else, such as a framework or a deserializer. The primary style of 0.18 is different: `Yavi.schema()` describes the properties of an input that does not exist yet and creates the typed object only when every property is valid. See [Object Validation](using-yavi.md) for the classic API and [Getting Started](getting-started.md) for the schema-first API.

## Constraints

Each annotation maps to a constraint method of the property. `@Min` and `@Max` are inclusive, so they map to `greaterThanOrEqual` and `lessThanOrEqual`; the exclusive forms are used only when `inclusive = false` is given.

### `@NotNull`

```java
.constraint(Foo::getText, "text", c -> c.notNull())
```

### `@Null`

```java
.constraint(Foo::getText, "text", c -> c.isNull())
```

### `@Pattern`

```java
.constraint(Foo::getText, "text", c -> c.pattern("[0-9]+"))
```

### `@Email`

```java
.constraint(Foo::getEmail, "email", c -> c.email())
```

### `@URL`

```java
.constraint(Foo::getUrl, "url", c -> c.url())
```

`url(url -> url.protocol("https").host("example.com").port(8443).build())` restricts the protocol, host and port. `c.uri()` accepts a URI with a scheme of any kind, such as `mailto:` or `s3://`.

### `@Min`

```java
.constraint(Foo::getIntValue, "intValue", c -> c.greaterThanOrEqual(1))
.constraint(Foo::getLongValue, "longValue", c -> c.greaterThanOrEqual(1L))
```

`@Min(value = 1, inclusive = false)` maps to `c.greaterThan(1)`.

### `@Max`

```java
.constraint(Foo::getIntValue, "intValue", c -> c.lessThanOrEqual(100))
.constraint(Foo::getLongValue, "longValue", c -> c.lessThanOrEqual(100L))
```

`@Max(value = 100, inclusive = false)` maps to `c.lessThan(100)`.

### `@Positive`

```java
.constraint(Foo::getIntValue, "intValue", c -> c.greaterThan(0))
```

### `@PositiveOrZero`

```java
.constraint(Foo::getIntValue, "intValue", c -> c.greaterThanOrEqual(0))
```

### `@Negative`

```java
.constraint(Foo::getIntValue, "intValue", c -> c.lessThan(0))
```

### `@NegativeOrZero`

```java
.constraint(Foo::getIntValue, "intValue", c -> c.lessThanOrEqual(0))
```

### `@DecimalMin`

```java
.constraint(Foo::getBigDecimalValue, "bigDecimalValue", c -> c.greaterThanOrEqual(new BigDecimal("1")))
```

`@DecimalMin(value = "1", inclusive = false)` maps to `c.greaterThan(new BigDecimal("1"))`.

### `@DecimalMax`

```java
.constraint(Foo::getBigDecimalValue, "bigDecimalValue", c -> c.lessThanOrEqual(new BigDecimal("100")))
```

`@DecimalMax(value = "100", inclusive = false)` maps to `c.lessThan(new BigDecimal("100"))`.

### `@Size`

```java
.constraint(Foo::getText, "text", c -> c.greaterThanOrEqual(4).lessThanOrEqual(64))
.constraint(Foo::getTexts, "texts", c -> c.greaterThanOrEqual(1).lessThanOrEqual(8))
```

The same methods apply to a string, a collection, an array and a map. The bounds are inclusive.

### `@NotEmpty`

```java
.constraint(Foo::getTexts, "texts", c -> c.notEmpty())
```

### `@NotBlank`

```java
.constraint(Foo::getText, "text", c -> c.notBlank())
```

### `@Digits`

```java
.constraint(Foo::getPrice, "price", c -> c.integerDigits(6).fractionDigits(2))
```

The constraints are available for a `BigDecimal`. Trailing zeros of the fraction are not counted: `1.500` has one fraction digit.

### `@AssertTrue`

```java
.constraint(Foo::getBooleanValue, "booleanValue", c -> c.isTrue())
```

### `@AssertFalse`

```java
.constraint(Foo::getBooleanValue, "booleanValue", c -> c.isFalse())
```

### `@Future`

```java
.constraint(Event::getStartsAt, "startsAt", c -> c.future())
```

### `@Past`

```java
Clock clock = Clock.fixed(Instant.parse("2026-01-01T00:00:00Z"), ZoneId.of("UTC"));
Validator<Event> validator = ValidatorBuilder.<Event>of()
        .constraint(Event::getCreatedAt, "createdAt", c -> c.past(clock))
        .build();
```

`past()` compares against the current time of the system default time zone. The `past(Clock)` overload reads the current time from the given `Clock`, so a test with `Clock.fixed` gives the same result on every run.

### `@FutureOrPresent`

```java
.constraint(Event::getStartsAt, "startsAt", c -> c.futureOrPresent())
```

### `@PastOrPresent`

```java
.constraint(Event::getCreatedAt, "createdAt", c -> c.pastOrPresent())
```

The temporal constraints are available for `Instant`, `LocalDate`, `LocalDateTime`, `LocalTime`, `OffsetDateTime`, `ZonedDateTime`, `Year` and `YearMonth`. The message keys are `temporal.future`, `temporal.past`, `temporal.futureOrPresent` and `temporal.pastOrPresent`.

## `@Valid`

### Nested Object

```java
public class OrderForm {

  @NotNull
  @Valid
  private AddressForm address;

  // omitted setter/getter

}
```

to

```java
Validator<AddressForm> addressValidator = ValidatorBuilder.<AddressForm>of()
        .constraint(AddressForm::getZipCode, "zipCode", c -> c.notNull().greaterThanOrEqual(1).lessThanOrEqual(10))
        .constraint(AddressForm::getAddress, "address", c -> c.notNull().greaterThanOrEqual(1).lessThanOrEqual(100))
        .build();

Validator<OrderForm> validator = ValidatorBuilder.<OrderForm>of()
        .nest(OrderForm::getAddress, "address", addressValidator)
        .build();
```

A violation of the nested object is located under its name, such as `address.zipCode`. `nestIfPresent` validates the nested object only when it is not `null`. In a schema, the same object is added with `_object`; see [Objects and Collections](objects-and-collections.md).

### Nested List, Array and Map

```java
public class OrderForm {

  @Valid
  private List<AddressForm> addresses;

  // omitted setter/getter

}
```

to

```java
Validator<OrderForm> validator = ValidatorBuilder.<OrderForm>of()
        .forEach(OrderForm::getAddresses, "addresses", addressValidator)
        .build();
```

`forEach` applies a validator to every element of a list, an array or a map value, and `forEachIfPresent` skips a `null` collection. The violations are located under the index (`addresses[0].zipCode`). A schema uses `_list`, `_map` and a nested `_object` instead.

## Custom Constraints

A Bean Validation `ConstraintValidator`:

```java
public class UpperCaseValidator implements ConstraintValidator<UpperCase, String> {

  @Override
  public boolean isValid(String value, ConstraintValidatorContext context) {
    return value == null || value.equals(value.toUpperCase());
  }

}
```

The counterpart is a `CustomConstraint`, which combines the predicate with its message key and default message:

```java
public enum UpperCaseConstraint implements CustomConstraint<String> {

    SINGLETON;

    @Override
    public boolean test(String value) {
        return value.equals(value.toUpperCase());
    }

    @Override
    public String messageKey() {
        return "custom.upperCase";
    }

    @Override
    public String defaultMessageFormat() {
        return "\"{0}\" must be upper case";
    }

}
```

```java
Validator<Foo> validator = ValidatorBuilder.<Foo>of()
        .constraint(Foo::getText, "text", c -> c.predicate(UpperCaseConstraint.SINGLETON))
        .build();
```

For a rule that is used once, `c.predicate(predicate, messageKey, defaultMessageFormat)` writes the predicate inline. See [Custom Constraints](custom-constraints.md).

## Differences

* There is no metadata layer and no annotations. A constraint is a Java expression, so the compiler and refactoring tools see it.
* There is no Bean Validation `Validation.buildDefaultValidatorFactory()` and no provider lookup. A validator is built with `ValidatorBuilder` or `Yavi.schema()`.
* A constraint is checked by the compiler: a method reference or a constraint method of the wrong type does not compile, while an annotation on a field of the wrong type is found at run time.
* Groups and conditional validation are available on `ValidatorBuilder` with `constraintOnGroup` and `constraintOnCondition`; see [Object Validation](using-yavi.md).
* A violation has a structured `path()`, a JSON `pointer()` and a `messageKey()`, so an API can return it directly; see [Violations](violations.md).
* Nullness is declared with JSpecify (`@Nullable`), and a nullness checker such as NullAway checks the use of a validated value; see [NullAway](integrations-nullaway.md).
* Schema-first input validation is the primary use case of 0.18. `Yavi.schema()` reads a map, a JSON tree or request parameters and creates the object only when every property is valid; `Yavi.arguments()` is deprecated in its favor. The classic `ValidatorBuilder` API is not deprecated.


---

# FILE: references/coming-from-zod.md

# Comparison with Zod

[Zod](https://zod.dev) is a schema and decoder for TypeScript: it validates untyped input and returns a typed value. YAVI 0.18 expresses the same model in Java: `Yavi.schema()` describes the properties of an input once, and the resulting validator reads that input from a map, a JSON tree or request parameters and creates an object only when every property is valid. This is the primary use case of 0.18.

The shape of a Zod program maps to YAVI as follows:

* A schema is described with `Yavi.schema()` and closed with `fromMap(f)`; the function `f` is the constructor of an ordinary Java record or class.
* The result type is the Java type that `f` returns, and the compiler checks it. There is no type inference (`z.infer`) and no generated schema type.
* The input is not one `unknown` value but a map, a JSON tree, request parameters or typed arguments; the same schema reads every form, and the form is chosen when the validator is used.
* Whether a property may be absent or `null` is part of the type: `nullable()` produces a `@Nullable` value and `optional()` an `Optional`, which a nullness checker (NullAway, Kotlin) and the compiler enforce.

## Basic

```ts
const User = z.object({
  email: z.string().email(),
  age: z.number().int().min(0),
  nickname: z.string().optional(),
});

const result = User.safeParse(JSON.parse(input));
if (result.success) {
  result.data; // { email: string; age: number; nickname?: string }
} else {
  result.error.issues;
}
```

```java
record User(String email, Integer age, Optional<String> nickname) {}

ObjectInputValidator<User> userValidator = Yavi.schema()
        ._string("email", c -> c.notBlank().email())
        ._integer("age", c -> c.greaterThanOrEqual(0))
        ._string("nickname").optional()
        .fromMap(User::new);

Map<String, Object> map = objectMapper.readValue(input, new TypeReference<>() {});
switch (userValidator.validate(map)) {
    case Validated.Valid<User>(User user) -> save(user);
    case Validated.Invalid<User>(ConstraintViolations violations) -> report(violations);
}
```

The schema validates the input, and only then does `User::new` run. The properties are given to the constructor as arguments, so the result is an ordinary record and the compiler checks that the schema describes it.

## Vocabulary

| Zod | YAVI |
| --- | --- |
| schema (`ZodType<Output, Input>`) | `ValueValidator<T, X>` (input `T`, output `X`). `Yavi.schema()` describes the properties; `fromMap(f)` or `apply(f)` makes a validator of them |
| `z.object({...})` | `Yavi.schema()._xxx(...).fromMap(f)` (`ObjectInputValidator<X>`) |
| `schema.safeParse(input)` | `validator.validate(input)` returns `Validated<X>` |
| `schema.parse(input)` | `validator.validated(input)` throws `ConstraintViolationsException` |
| `result.success` / `result.data` / `result.error` | `Validated.Valid(value)` / `Validated.Invalid(errors)`, a sealed interface |
| issue (`code`, `path`, `message`) | `ConstraintViolation` (`messageKey()`, `path()`, `message()`) |
| `z.infer<typeof schema>` | the result type of the function given to `fromMap` / `apply` |

## Schemas

| Zod | YAVI |
| --- | --- |
| `z.string()`, `z.number()`, `z.boolean()`, `z.date()` ... as a property | `_string(name, c -> ...)`, `_integer`, `_long`, `_double`, `_bigDecimal`, `_boolean`, `_localDate`, `_instant` ... |
| the same as a schema of its own | `Yavi._string(c -> ...)`, `Yavi._integer(c -> ...)` ... |
| `z.enum([...])` | `_enum(name, Role.class)`; `_enum(Yavi._enum(name, Role.class).ignoringCase())` reads the name in any case |
| `z.object({...})` nested | `_object(name, anotherObjectInputValidator)` |
| `z.array(schema)` | `_list(name, elementValidator)`, `validator.liftList()` |
| `z.record(z.string(), schema)` | `_map(name, valueValidator)`, `validator.liftMap()` |
| `z.array(schema).nonempty().min(1).max(10)` | `_list(name, elementValidator, c -> c.notEmpty().greaterThanOrEqual(1).lessThanOrEqual(10))`, `Yavi._list(elementValidator, c -> ...)` (also `unique()`, `contains(...)`) |
| `z.record(z.string(), schema)` with a size | `_map(name, valueValidator, c -> c.notEmpty())`, `Yavi._map(valueValidator, c -> ...)` |
| `.optional()` | `.optional().rejectingNull()` (produces `Optional<X>`) |
| `.nullable()` | `.nullable().required()` (produces `@Nullable X`) |
| `.nullish()` | `.optional()` or `.nullable()` |
| `.optional()` with `undefined` told from a value in the result | `.presence()` (produces `Presence<X>`) |
| `.nullable().optional()` / `.nullish()` with the two told apart in the result | `.nullable().presence()` |
| `.default(value)` | `.defaultValue(value).rejectingNull()`; `.defaultValue(value)` also replaces `null` |
| `.catch(value)` | `.recover(value)` (also for `null` and an absent key) |
| `.catch(ctx => ...)` | `.recoverWith(violations -> ...)` |
| `z.union([a, b])` | `ValueValidator.anyOf(a, b)` |
| `z.discriminatedUnion("type", [...])` | `DiscriminatedUnionValidator.<X>of("type").when("circle", a).when("square", b)` |
| `z.lazy(() => schema)`, a getter that refers to the schema | `ValueValidator.lazy(() -> validator)`, `ValueValidator.recursive(self -> ...)` |
| `z.number().multipleOf(n)` | `c.multipleOf(n)` of the integral types, `BigInteger` and `BigDecimal` (not of `Double` and `Float`) |
| `z.email()`, `z.uuid()`, `z.ipv4()`, `z.ipv6()`, `z.ulid()` | `c.email()`, `c.uuid()`, `c.ipv4()`, `c.ipv6()`, `c.ulid()` |
| `z.union([z.ipv4(), z.ipv6()])` | `c.ip()` |
| `z.url()` | `c.uri()` (any scheme), `c.url()` (a protocol of `java.net.URL`) |
| `z.cuid()`, `z.cuid2()` | `c.pattern(regex)` |
| `.refine(predicate)` on a value | a constraint (`c -> c.predicate(...)`) |
| `.refine(predicate)` on an object | `.constraintOnTarget(predicate, name, violationMessage)` |
| `.transform(f)` | `.map(f)` |
| `z.string().trim().toLowerCase()`, `.toUpperCase()`, `.normalize()` | `_string(name, c -> c.trim().toLowerCase()...)`, `c.toUpperCase()`, `c.toNormalForm(form)`, `c.transform(f)`, written before the constraints |
| `z.preprocess(f, schema)` | `validator.preprocess(f)` for a value of the same type |
| `.pipe(schema)` | `.andThen(validator)` |
| `z.unknown()` / `z.any()` | `_object(name, Object.class)` |
| `z.object({...})` (strips unknown keys) | the default of `fromMap` |
| `z.strictObject({...})` | `.rejectingUnknownProperties()` |
| `z.looseObject({...})` | `._rest()` |
| `z.object({...}).catchall(schema)` | `._rest(valueValidator)` |
| `a.extend(b.shape)`, `z.intersection(a, b)` of objects | `._embedded(b)`, which gives the object of `b` to the function |
| `z.toJSONSchema(schema)` | `JsonSchema.of(validator.description())` |

The constraints are listed in [Built-in Constraints](built-in-constraints.md); the combinators of a value are described in [Defining a Schema](defining-a-schema.md).

## Inputs

A Zod schema always takes `unknown`, which in practice is what `JSON.parse` returns. In Java the input has several forms, and the same properties are read from all of them. The schema is written once with `fromMap(f)`, and the form of the input is chosen last:

| Input | Zod | YAVI | Input type |
| --- | --- | --- | --- |
| A parsed JSON document as a map | `schema.safeParse(JSON.parse(input))` | `validator` | `Map<String, Object>` |
| A value of unknown type | `schema.safeParse(input)` | `validator.untyped()` | `Object` |
| The tree model of a JSON library | | `validator.readingWith(reader)` | the node type, such as `JsonNode` |
| Request parameters, a submitted form | `z.coerce`, `zod-form-data` | `validator.readingParameters()` | `Map<String, String>`, `Map<String, List<String>>`, `Map<String, String[]>` |
| Typed arguments | | `Yavi.schema()...apply(f)` | the types of the arguments |

### A map or a value of unknown type

`fromMap(f)` builds a validator of a `Map<String, Object>`. `untyped()` turns it, and any other validator that knows its input type, into a `ValueValidator<Object, X>`, which is the counterpart of a Zod schema:

```java
ValueValidator<Object, User> any = userValidator.untyped(); // rejects anything but a map
ValueValidator<Object, Object> id = ValueValidator.anyOf(Yavi._string(c -> c.notBlank()).untyped(),
        Yavi._integer(c -> c.positive()).untyped());
```

The input type must be known when the validator is built. `fromMap` and `untyped()` throw for a lambda or an `_enum` / `_object` property added without a type; give it with `untyped(type)`, `_enum(name, type)` or `_object(name, type)`. See [Maps and Untyped Values](input-maps.md).

### The tree model of a JSON library

`readingWith(reader)` binds a validator to an `InputReader`, which tells how to read the nodes of a tree model. The tree is validated without being copied to a map. `from(reader, f)` builds such a validator from the schema:

```java
ValueValidator<JsonNode, User> nodeValidator = userValidator.readingWith(JsonNodeReader.INSTANCE);
ValueValidator<JsonNode, User> same = Yavi.schema()
        ._string("email")
        .from(JsonNodeReader.INSTANCE, User::new);
```

YAVI has no dependency on a JSON library; a reader is a small class written once per tree model. [Jackson](integrations-jackson.md) shows a reader.

### Request parameters

Request parameters and a submitted form are a flat map of strings. `readingParameters()` reads it with the properties written as for a JSON document:

```java
ValueValidator<Map<String, ?>, SearchForm> validator = Yavi.schema()
        ._integer("page", c -> c.greaterThanOrEqual(1)).defaultValue(1)
        ._boolean("includeArchived").defaultValue(false)
        ._list("tags", tagValidator).defaultValue(List.of())
        ._object("address", addressValidator).nullable()
        .fromMap(SearchForm::new)
        .readingParameters();

// page=2&includeArchived=true&tags=a&tags=b&address.city=Tokyo
validator.validate(parameters);
```

It does what Zod needs two things for:

* The values are strings that stand for the type of their property, which is `z.coerce` in Zod. The rules are in [Strings](#strings).
* The keys are paths (`address.city`, `items[0].name`) and a key with several values is a list, which is what `zod-form-data` adds to Zod for a `FormData`. See [Request Parameters and Forms](input-parameters.md).

An empty list cannot be sent, so a list that may be empty has `defaultValue(List.of())`.

### Typed arguments

In Java the input is usually already bound to a type, so a YAVI validator is typed first (`ValueValidator<String, Email>`). `apply(f)` builds a validator of typed arguments from the schema that `fromMap(f)` builds a validator of a map from. Zod has no counterpart: its schemas check the type and the constraints together. See [Typed Arguments](input-arguments.md).

## Rules that differ

### Absent and `null`

Like a Zod schema, a property is required unless it says otherwise, and saying otherwise changes its type: `nullable()` produces `@Nullable X` and `optional()` `Optional<X>`, as `z.infer` gives `X | null` and `X | undefined`. A nullness checker that reads JSpecify (NullAway, Kotlin) therefore rejects a function that takes a `nullable()` property as a value that is not `null`.

Zod tells `undefined` (`optional()`) from `null` (`nullable()`). In YAVI an absent key is validated like `null`, so `optional()`, `nullable()` and `defaultValue(...)` accept both. Only the violation differs for a required property: an absent key is reported with `object.required` and an explicit `null` with `object.notNull`, or with the violation of a constraint that rejects `null` such as `notBlank()`.

The last modifier of a property keeps the two apart as Zod does. `required()` rejects an absent key although `null` is accepted, and `rejectingNull()` rejects an explicit `null` although the key may be absent. The type of the value does not change.

```ts
const Account = z.object({
  deletedAt: z.iso.datetime().nullable(), // the key is required
  middleName: z.string().optional(),      // null is rejected
  page: z.number().int().default(1),      // null is rejected
});
```

```java
record Account(@Nullable Instant deletedAt, Optional<String> middleName, int page) {}

ObjectInputValidator<Account> accountValidator = Yavi.schema()
        ._instant("deletedAt").nullable().required()
        ._string("middleName").optional().rejectingNull()
        ._integer("page").defaultValue(1).rejectingNull()
        .fromMap(Account::new);
```

`presence()` gives the three states to the created object, for a partial update (PATCH). The property is a `Presence<X>`: `Absent` for an absent key, which is not validated, and otherwise what the property makes of the value, `null` included.

```java
record ProfilePatch(Presence<String> nickname, Presence<String> bio) {}

ObjectInputValidator<ProfilePatch> patchValidator = Yavi.schema()
        ._string("nickname", c -> c.lessThanOrEqual(50)).presence()
        ._string("bio", c -> c.lessThanOrEqual(500)).nullable().presence()
        .fromMap(ProfilePatch::new);
```

See [Optional and Default Values](optional-and-defaults.md).

### Unknown keys

Both ignore unknown keys unless the object is strict. `rejectingUnknownProperties()` reports them with the message key `object.unknownProperty`, which catches a typo in an optional property; like `z.strictObject`, it applies to that object only.

The counterpart of `.catchall(schema)` and `z.looseObject` is an argument: the result is created by a function, so the extra keys are given to it as a map. `_rest(valueValidator)` validates their values and `_rest()` takes them as they are.

```java
record Item(String name, Map<String, String> attrs) {}

ObjectInputValidator<Item> itemValidator = Yavi.schema()
        ._string("name", c -> c.notBlank())
        ._rest(Yavi._string(c -> c.notBlank()))
        .fromMap(Item::new);
```

### Types

Both are exact by default: `"30"` is not a number. YAVI accepts the representation a JSON document has for the type of the property:

* a number whatever its Java type is, as long as the value is kept (`30L` and `30.0` are an `Integer`, `30.5` is not),
* the name of a constant for an enum,
* an ISO-8601 string for `LocalDate`, `Instant` and the other temporal types, `Duration` and `Period`,
* the string form of a `UUID` and a `URI` (`_object("id", UUID.class)`).

A mismatch is reported with `object.type` (`"age" must be of type integer`).

### Strings

`z.coerce` is chosen per schema and converts with the JavaScript constructors (`Number(input)`, `Boolean(input)`). In YAVI the coercion of strings belongs to the input, not to a property, so the schema does not change:

* `readingParameters()` coerces the strings of request parameters.
* `CoercibleInputReader#coercingStrings()` decorates a reader of a tree model, for a tree whose scalars are all strings: `validator.readingWith(JsonNodeReader.INSTANCE.coercingStrings())` reads a JSON document whose numbers are sent as strings.

Both follow the same rules, which are stricter than `z.coerce`:

| Input | `z.coerce` | YAVI |
| --- | --- | --- |
| `""` for a number | `0` | `null`, so `optional()` and `defaultValue` apply |
| `" 30 "` for a number | `30` | `object.type`; `30` with `trimming()` |
| `" a "` for a string | `" a "`; `"a"` with `.trim()` | `" a "`; `"a"` with `trimming()` or `c.trim()` |
| `"0x1e"` for a number | `30` | `object.type` |
| `"false"` for a boolean | `true` | `false` |
| `"on"`, `"1"` for a boolean | `true` | `object.type`; `true` with `booleanWords()`, like `z.stringbool()` |
| `30` for a string | `"30"` | `object.type` |

`trimming()` and `booleanWords()` are options of `StringCoercion`, given to `readingParameters(coercion)` or `coercingStrings(coercion)`:

```java
validator.readingParameters(StringCoercion.strict().trimming().booleanWords());
```

This reads a submitted form, whose checked checkbox sends `on`. An empty string is `null` for a string property too.

### Unions

`z.union` and `ValueValidator.anyOf` try the alternatives in order and report one issue when none matches: `invalid_union` with `errors`, the issues of each alternative, and `object.anyOf`, a `ConstraintViolation.NoAlternativeMatched` with `alternatives()`, the violations of each alternative (`alternatives` of a `ViolationDetail.NoAlternativeMatched`). `DiscriminatedUnionValidator` applies only the alternative selected by the discriminator, like `z.discriminatedUnion`. An alternative does not have to define the discriminator as `z.literal(...)`: the key is hidden from an alternative that does not define it. See [Unions](unions.md).

### Errors

A `ConstraintViolation` has a message key instead of an issue code, and the message is formatted with a `MessageFormatter`, so it can be localized. `path()` is a list of `PathSegment.Property` and `PathSegment.Index`, `name()` is its flat form (`address.street`, `tags[0]`) and `pointer()` its JSON Pointer (`/address/street`, `/tags/0`).

| Zod | YAVI |
| --- | --- |
| `z.flattenError(error)` | `violations.messagesByName()`, a map of the name to the messages; the messages of the root are under the empty name |
| `error.issues` as JSON | `violations.details()`, a list of `ViolationDetail` (`name`, `pointer`, `messageKey`, `message`, `params`, and `alternatives` for `object.anyOf`) |
| `issue.minimum`, `issue.maximum`, `issue.format` and so on | `params` of a detail, `violation.params()` (`{"max": 150}`); the violated value is not in it |

`z.treeifyError` has no counterpart: the keys of `messagesByPointer()` address the nested values instead. See [Violations](violations.md).

## Codecs

`z.codec(input, output, { decode, encode })` and `z.encode(schema, value)` are a validator that writes what it reads:

| Zod | YAVI |
| --- | --- |
| `z.codec(z.string(), z.custom<Email>(), { decode, encode })` | `Yavi._string("email", c -> c.email()).map(Email::new, Email::value)` (`ReversibleValueValidator`) |
| `z.encode(codec, value)` | `validator.reverse(value)` |
| `z.encode(objectSchema, value)` | `Yavi.reversibleSchema()...fromMapReversible(f, accessor1, ...)`, then `validator.toMap(value)` |

A validator that does not know its reverse, such as `map(f)`, is the counterpart of a transform, which Zod refuses to encode at run time. YAVI refuses it at compile time: it is not a `ReversibleValueValidator`, which a schema of `Yavi.reversibleSchema()` takes. See [Writing an Object Back](writing-back.md).

## Not available

* Object schema operations that derive a schema: `pick`, `omit`, `partial`. `extend` and `merge` are `_embedded`, which keeps the object of the embedded validator.
* `z.tuple` and `z.literal` as a schema (use the `equalTo` / `oneOf` constraints).
* Asynchronous refinements and transforms.
* More than 16 properties in one schema; group them with `_embedded`, or use `ObjectInputValidator.of(parts, mapper)`.


---

# FILE: references/concepts.md

# Core Concepts

This page explains the pieces every schema uses: how input becomes an object, what a schema and a validator are, how results and violations are represented, and what the type system checks.

## Input and validated object

Reading an input is a pipeline:

1. The input is parsed by the caller or by an `InputReader`: a `Map<String, Object>`, a JSON node, request parameters, or typed arguments.
2. Each property is read by name and its type is checked against the property method.
3. The constraints of the property are evaluated.
4. When every property is valid, the validated values are passed to the function given to `fromMap(f)` or `apply(f)`, which creates the object.

A failure at any step ends the pipeline for that property. The remaining properties are still checked, and every violation is collected. The function that creates the object is not called when there is at least one violation.

Nested objects, lists and maps repeat the same pipeline at their own level. Their violations are located under the property name, for example `address.street`, `roles[0]` or `scores.math`.

## Schemas and typed validators

`Yavi.schema()` returns a builder whose methods add properties. A schema in progress is not a validator: it cannot validate anything until `fromMap(f)` or `apply(f)` ends it. The builder is immutable: each call returns a new stage, and the schema is not reused or mutated. `fromMap(f)` ends it with an `ObjectInputValidator<X>`, and `apply(f)` ends it with an `ArgumentsNValidator<..., X>`.

Both are `ValueValidator`s. A `ValueValidator<I, X>` knows its input type `I` and the type `X` it produces. The same description can therefore be given another input type with `readingWith(reader)` or `untyped()`, and it can be nested as a property of another schema.

A validator of a single value, such as `Yavi._string("email", c -> c.email())`, is a `ValueValidator<String, String>`. It validates one value and can be used on its own, as a list element, or as a property.

## Validated and violations

`Validated<T>` is a sealed interface:

* `Validated.Valid<T>` holds the created object in `value()`.
* `Validated.Invalid<T>` holds a `ConstraintViolations` in `errors()`.

`validate` plays the role of `safeParse` in a Zod-style API; the name is kept from 0.17.

`ConstraintViolations` is a list of `ConstraintViolation`. Each violation exposes:

* `name()`: the flat name, such as `address.street` or `tags[1]`.
* `path()`: the structured path, as `PathSegment.Property` and `PathSegment.Index`.
* `pointer()`: the same location as a JSON Pointer (RFC 6901), such as `/address/street`.
* `messageKey()` and `message()`: the key and the formatted message.
* `args()` and `violatedValue()`: the positional arguments and the value that failed.

`messagesByName()` and `messagesByPointer()` group the messages for a form or an API response, and `details()` returns `ViolationDetail` records that are safe to serialize. The violated value is not part of a detail.

## Required and nullable values

A property of a schema is required unless a modifier says otherwise. An absent key and an explicit `null` are both violations for a required property, with different message keys (`object.required` and `object.notNull`).

The modifier changes the type of the validated value:

* `nullable()` produces `@Nullable X`.
* `optional()` produces `Optional<X>`.
* `defaultValue(v)` and `recover(v)` produce `X` and never fail for `null`.

The compiler and a nullness checker see these types. A modifier that has no effect, such as `.nullable().optional()`, does not compile. `presence()` is the exception: it produces a `Presence<X>` that keeps `Absent`, `PresentNull` and `Present` apart.

`ValidatorBuilder` follows the other model: a property that is `null` is valid unless a constraint rejects it.

## JSpecify nullness

YAVI is annotated with [JSpecify](https://jspecify.dev). The annotations are `provided`, so YAVI does not add a runtime dependency, and an application that declares `@Nullable` values adds `org.jspecify:jspecify` itself.

With NullAway or the Kotlin compiler, the annotations are checked across the API:

* A function given to `fromMap` or `apply` receives a non-null parameter unless the corresponding property is `nullable()`.
* A value declared as `ValueValidator<String, @Nullable String>` must be handled as nullable.
* `fromMap(User::new)` does not compile when a `nullable()` property is passed to a parameter that is not `@Nullable`.

See [NullAway](integrations-nullaway.md) for the checks and their limitations.

## Thread safety

A schema and a validator are immutable. A validator built once can be stored in a `static final` field and used concurrently by any number of threads. Violations and `Validated` results are created per call.

The functions given to `fromMap`, `apply` and the constraints are called during validation. They must be thread-safe themselves if the validator is shared.

## Compile-time and run-time checks

The compiler checks:

* that a constraint exists for the type of the value it is applied to,
* that a modifier chain is meaningful, because the stages change the available methods,
* that the function given to `fromMap` or `apply` accepts the types the schema produces, including nullness where a checker is enabled,
* that a reversible schema receives a validator that knows how to write the value back.

The run time checks:

* that each input value represents the declared type,
* that each constraint holds,
* that required keys are present.

No check depends on reflection or on annotations being retained at run time.


---

# FILE: references/cross-field-rules.md

# Cross-Field Rules

Some rules involve more than one property. This page describes `constraintOnTarget`, the factories that can fail, and how such violations are located and accumulated.

## Rules on the created object

`constraintOnTarget(predicate, name, violationMessage)` adds a rule that the created object must satisfy. It is available on the validator returned by `fromMap` and on a single-value validator:

```java
ObjectInputValidator<PasswordForm> passwordFormValidator = Yavi.schema()
        ._string("currentPassword", c -> c.notBlank())
        ._string("newPassword", c -> c.greaterThanOrEqual(8))
        ._string("confirmPassword", c -> c.notBlank())
        .fromMap(PasswordForm::new)
        .constraintOnTarget(form -> form.newPassword().equals(form.confirm()), "confirmPassword",
                ViolationMessage.of("password.mismatch", "\"{0}\" must match \"newPassword\""))
        .constraintOnTarget(form -> !form.current().equals(form.newPassword()), "newPassword",
                ViolationMessage.of("password.same", "\"{0}\" must differ from \"currentPassword\""));
```

* The predicate is evaluated only when every property is valid.
* The rule is reported under the name given as the second argument, so a form can show it next to a field. The name is also the `{0}` of the message.
* Rules added one after another are all checked, and every violated rule is reported.
* The result is still an `ObjectInputValidator`, so `rejectingUnknownProperties()`, `readingParameters()` and `constraintOnTarget` can follow.
* The predicate sees the created object. A value that the object does not keep cannot be read here; see below.

A custom `ValueValidator` that overrides `constraintOnTarget` keeps its rules in a `TargetConstraints`: `and` adds a rule and `check` reports every rule that a value violates.

## Locating violations

The second argument of `constraintOnTarget` is the name of the violation, `name()`, `path()` and `pointer()` follow from it. A name that is a property of the object locates the violation at that property. A name that is empty locates it at the object.

For a rule over several fields, choose a field that the user can correct, such as `confirmPassword` for a password mismatch, rather than the object itself. A form can then show the message next to that field with `messagesByName()`.

## Fallible factories

`flatFromMap(f)` and `flatApply(f)` take a function that creates the object and can fail. The function returns a `Validated` and is applied only when all arguments are valid:

```java
record DateRange(LocalDate start, LocalDate end) {

    static Validated<DateRange> of(LocalDate start, LocalDate end) {
        return start.isBefore(end) ? Validated.successWith(new DateRange(start, end))
                : Validated.failureWith(ViolationMessage.of("dateRange.invalid", "start must be before end"));
    }

}

ObjectInputValidator<DateRange> dateRangeValidator = Yavi.schema()
        ._localDate("start")
        ._localDate("end")
        .flatFromMap(DateRange::of);

dateRangeValidator.validate(Map.of("start", "2025-12-31", "end", "2025-01-01"))
        .errors().get(0).locale(); // the locale of the validation
```

* `Validated.failureWith(ViolationMessage.of(key, format))` creates one violation. Its name is empty, so it is reported on the map itself and takes the name of the property the validator is applied to.
* The function is not given the locale of the validation. The violations it returns are reported with that locale, whichever locale they were created with. `localizedWith(locale)` does the same for a violation created elsewhere.
* A violation that must be located at a property is created with a `ConstraintViolation` that has that name, or the rule is written as `constraintOnTarget`.
* `flatApply(f)` is the counterpart for typed arguments.

## Values not kept in the result

`constraintOnTarget` sees only the created object. When a validated value is not stored in that object, such as the confirmation of a password, a rule that reads it is written in the factory, which receives every validated argument:

```java
record PasswordChange(String newPassword) {}

ObjectInputValidator<PasswordChange> passwordChangeValidator = Yavi.schema()
        ._string("newPassword", c -> c.greaterThanOrEqual(8))
        ._string("confirmPassword", c -> c.notBlank())
        .flatFromMap((newPassword, confirmPassword) -> newPassword.equals(confirmPassword)
                ? Validated.successWith(new PasswordChange(newPassword))
                : Validated.failureWith(ViolationMessage.of("password.mismatch", "passwords must match")));
```

The same applies to a value that is read from the input only to check it. Declare it as a property, so it is validated and described, and let the factory decide what to store.

## Evaluation order

A validation runs in this order:

1. The properties are read and their types are checked.
2. The constraints of each property are evaluated. Violations are accumulated; the remaining properties are still checked.
3. `constraintOnTarget` rules are evaluated, only when every property is valid. Every rule is checked.
4. The factory given to `fromMap`, `flatFromMap`, `apply` or `flatApply` is called, only when there is no violation. A rule added after `map` or `andThen` on a single-value validator is checked only when the rules before it hold.

Because the properties are validated before the rules, a cross-field rule never hides a field violation. Because the rules are accumulated, a request reports every failed rule at once.


---

# FILE: references/custom-constraints.md

# Custom Constraints

A constraint that the built-in constraints do not cover is written as a predicate. The predicate is applied with `predicate` on the constraint of the value, and the violation is reported like that of a built-in constraint.

## A predicate constraint

`predicate` takes the predicate, a message key and a message format.

```java
Validator<Book> validator = ValidatorBuilder.<Book>of()
        ._string(Book::title, "title", c -> c.notBlank().lessThanOrEqual(64))
        ._string(Book::isbn, "isbn", c -> c.notBlank()
                .predicate(ISBNValidator::isISBN13, "string.isbn13", "\"{0}\" must be ISBN13 format"))
        .build();
```

`{0}` is the name of the property and the last placeholder is the value that violated the constraint. Override `arguments` of a custom constraint, described below, to add arguments between them.

`predicateNullable` is the same for a predicate that accepts `null`; it does not reject a `null` value before the predicate runs.

## A custom constraint class

`am.ik.yavi.core.CustomConstraint<V>` combines a predicate with its message key, its default message format and its arguments, so that one constraint is defined once and applied in several places.

```java
public final class Isbn13Constraint implements CustomConstraint<String> {

    @Override
    public boolean test(String isbn) {
        if (isbn == null || !isbn.matches("[0-9]{13}")) {
            return false;
        }
        int sum = 0;
        for (int i = 0; i < 12; i++) {
            int digit = isbn.charAt(i) - '0';
            sum += (i % 2 == 0) ? digit : digit * 3;
        }
        return (10 - sum % 10) % 10 == isbn.charAt(12) - '0';
    }

    @Override
    public String messageKey() {
        return "string.isbn13";
    }

    @Override
    public String defaultMessageFormat() {
        return "\"{0}\" must be ISBN13 format";
    }

}
```

Apply it with `predicate`. The predicate is also usable in a rule on the target object, with the message of that rule:

```java
Validator<Book> validator = ValidatorBuilder.<Book>of()
        ._string(Book::isbn, "isbn", c -> c.notBlank().predicate(new Isbn13Constraint()))
        .build();

Validator<Book> checked = ValidatorBuilder.<Book>of()
        ._string(Book::isbn, "isbn", c -> c.notBlank())
        .constraintOnTarget(book -> new Isbn13Constraint().test(book.isbn()), "isbn",
                "string.isbn13", "\"{0}\" must be ISBN13 format")
        .build();
```

## Message keys and arguments

The message key identifies the violation. The default message format is used when no `MessageFormatter` has a message for that key, and `{0}` is the name of the property. A constraint that needs more arguments overrides `arguments`, which are inserted between the name and the violated value. The violated value is appended as the last argument.

```java
public final class InstantRangeConstraint implements CustomConstraint<Instant> {

    private final Instant start;

    private final Instant end;

    public InstantRangeConstraint(Instant start, Instant end) {
        this.start = Objects.requireNonNull(start);
        this.end = Objects.requireNonNull(end);
    }

    @Override
    public Object[] arguments(Instant violatedValue) {
        return new Object[] { this.start /* {1} */, this.end /* {2} */ };
    }

    @Override
    public String defaultMessageFormat() {
        return "Instant value \"{0}\" must be between \"{1}\" and \"{2}\".";
    }

    @Override
    public String messageKey() {
        return "instant.range";
    }

    @Override
    public boolean test(Instant instant) {
        return instant.isAfter(this.start) && instant.isBefore(this.end);
    }

}
```

A message of your own that a client reads from `ViolationDetail` names its arguments, so that a client can render the message from `messageKey` without knowing the positions. Override `paramNames` with the names of the arguments from `{1}` on; the violated value gets no name unless it is meant to be returned.

```java
@Override
public List<String> paramNames() {
    return List.of("start", "end");
}
```

A `ViolationMessage` created with `ViolationMessage.of(key, format, "start", "end")` names the arguments in the same way.

## Reusing a constraint across types

A `CustomConstraint` is typed by the value it tests. Write the class once and pass an instance wherever a value of that type is constrained: with `_string` in a validator of an object, with `Yavi._string` in a validator of a single value, and with `constraintOnTarget` when the value is the target. The message key and the arguments travel with the instance.

```java
private static final CustomConstraint<String> ISBN = new Isbn13Constraint();

Validator<Book> bookValidator = ValidatorBuilder.<Book>of()
        ._string(Book::isbn, "isbn", c -> c.notBlank().predicate(ISBN))
        .build();

StringValidator<String> isbnValidator = Yavi._string("isbn", c -> c.notBlank().predicate(ISBN));
```

When only the rule is shared, `predicate(Predicate, ViolationMessage)` applies the same predicate with the message of the property that uses it.


---

# FILE: references/defining-a-schema.md

# Defining a Schema

A schema is a sequence of property methods on `Yavi.schema()`. Each method gives the type and the name of an input value, and a lambda adds its constraints. `fromMap(f)` or `apply(f)` ends the schema with a validator.

```java
import am.ik.yavi.input.ObjectInputValidator;
import am.ik.yavi.validator.Yavi;

record Signup(String email, Integer age) {}

ObjectInputValidator<Signup> signupValidator = Yavi.schema()
        ._string("email", c -> c.notBlank().email())
        ._integer("age", c -> c.greaterThanOrEqual(0).lessThanOrEqual(150))
        .fromMap(Signup::new);
```

## Property methods

The methods have the names of the Java types they read:

| Type | Methods |
| --- | --- |
| Text | `_string` |
| Integral numbers | `_integer`, `_long`, `_short`, `_bigInteger` |
| Fractional numbers | `_double`, `_float`, `_bigDecimal` |
| Boolean | `_boolean` |
| Enum | `_enum(name, type)` |
| Date and time | `_localDate`, `_localTime`, `_localDateTime`, `_instant`, `_offsetDateTime`, `_zonedDateTime`, `_year`, `_yearMonth` |
| Other values | `_object(name, type)`, for example `UUID.class`, `URI.class`, `Duration.class` or `Period.class` |
| Containers | `_list`, `_map`, `_object(name, nestedValidator)`, `_embedded`, `_rest` |

Every method has overloads without constraints (`._string("name")`) and without a name (`Yavi._string(c -> ...)`), which is described below. A temporal value is read from its ISO-8601 text, an enum from the name of its constant, and a `UUID` or a `URI` from its string form.

In Kotlin, the extension functions of `am.ik.yavi.builder` take the type of an enum or an object as a type argument and pass it to the Java method, so no `Class` literal is needed:

```kotlin
import am.ik.yavi.builder._enum
import am.ik.yavi.builder._object

Yavi.schema()
    ._enum<Role>("role") { it.oneOf(Role.ADMIN) }
    ._object<UUID>("id")
    .apply(::Account)
```

## Constraints

The lambda receives the constraint object of the type. Its methods are the constraints that apply to that type:

```java
Yavi.schema()
        ._string("licensePlate", c -> c.notBlank().greaterThanOrEqual(2).lessThanOrEqual(14).pattern("[A-Z0-9-]+"))
        ._integer("seatCount", c -> c.greaterThanOrEqual(2).lessThanOrEqual(9))
        ._bigDecimal("price", c -> c.positive().fractionDigits(2).integerDigits(6))
        ._boolean("agreed", c -> c.isTrue())
        ._enum("role", Role.class, c -> c.oneOf(Role.ADMIN, Role.MEMBER))
        ._localDate("birthday", c -> c.before(() -> LocalDate.now()))
        .fromMap(Profile::new);
```

A constraint that does not exist for the type cannot be written, so a length constraint on an `Integer` is a compile error. The complete list is in [Built-in Constraints](built-in-constraints.md).

A constraint accepts the empty string unless `notBlank()` or `notEmpty()` is added: `email()` describes the form of a value, not that it is given.

## Names and messages

The first argument is the key of the property in the input and the name of its violations. It is also the name that appears in a message, unless a label is set:

```java
Yavi.schema()
        ._string("name", c -> c.notBlank()).label("Token name")
        ._integer("ttl", c -> c.positive()).typeMessage("\"{0}\" must be a number of seconds")
        ._list("roles", Yavi._string()).required("Select at least one role")
        .fromMap(Token::new);
```

* `label(text)` replaces `{0}` of every message of the property and its elements. The violation keeps its `name()`, `path()` and `pointer()`.
* `typeMessage(text)` replaces the message of `object.type`, which reports a value of another type.
* `required(text)` replaces the message of `object.required`, which reports an absent key.
* `message(text)` after a constraint replaces the message of that constraint.

Each of these also accepts a `ViolationMessage`, whose key a resource bundle can localize:

```java
c -> c.notBlank().message(ViolationMessage.of("user.name.notBlank", "Enter your name"))
```

A name that is defined twice in one schema is rejected when the schema is built.

## String transforms

A `String` can be transformed before its constraints. The transforms are written in the order they are applied, and the constraints and the produced value see the transformed text:

```java
StringValidator<String> emailValidator = Yavi._string("email",
        c -> c.trim().toLowerCase().toNormalForm(Normalizer.Form.NFC).notBlank().email());

emailValidator.validate("  USER@Example.COM "); // Valid[value=user@example.com]
```

The transforms are `trim()`, `toLowerCase()`, `toUpperCase()`, `toNormalForm(form)` and `transform(f)`. A `null` value is not transformed.

Any other type is transformed with `preprocess`, and a value of another type is adapted with `compose`; see [Value Objects and Transforms](value-objects.md).

## Reusing a single-value validator

A validator of one value is written with the `Yavi` methods that have the names of the property methods:

```java
public static final StringValidator<String> emailValidator =
        Yavi._string("email", c -> c.trim().notBlank().email());
```

A schema takes it as a property of the same name, and `named(name)` applies it under another key:

```java
ObjectInputValidator<Contact> contactValidator = Yavi.schema()
        ._string(emailValidator)                                  // the key is "email"
        ._string(emailValidator.named("backupEmail")).nullable()  // the key is "backupEmail"
        .fromMap(Contact::new);
```

A validator may omit its name when its place gives it one, such as the element of a list: `Yavi._string(c -> c.notBlank())`. Validated alone, its violation has the empty name and its message says "The value" instead of the name.

`_object(name, validator)` uses a nested validator under `name`. The combinators carry the name, so `emailValidator.map(Email::new).named("contact")` and `emailValidator.named("contact").map(Email::new)` are the same.

## Required properties

A property is required. An absent key is reported with `object.required`, and an explicit `null` with `object.notNull` or with the violation of a constraint that rejects `null`, such as `notBlank()`. The function given to `fromMap` is not called with `null` for a required property.

A property that may be `null` or absent says so with `nullable()`, `optional()`, `presence()` or `defaultValue(...)`. These modifiers are described in [Optional and Default Values](optional-and-defaults.md).


---

# FILE: references/describing-a-schema.md

# Describing a Schema

A validator describes the input it expects. This page shows the description tree, the JSON Schema generated from it, and what cannot be described.

## Descriptions

`description()` returns a read-only `ValueDescription`: a tree of objects with properties, lists, maps, alternatives and values with their constraints. A tool can walk it without the classes the validator was built from.

```java
ValueDescription description = userValidator.description();

ValueDescription.Properties object = (ValueDescription.Properties) description;
for (ValueDescription.Property property : object.properties()) {
    System.out.println(property.name() + ": " + property.value());
}
```

A constraint is described by its message key and arguments, for example `container.lessThanOrEqual` with `[14]`. A property that is withheld is marked as such. The description carries the name of the property and, for a nested value, its structure.

The description is immutable and is built from the schema, not from an input. A schema that reads a map, a JSON tree and request parameters has one description, because the properties are the same.

## JSON Schema

`JsonSchema` is a consumer of the description. It needs no JSON library:

```java
Map<String, Object> schema = JsonSchema.of(userValidator.description());
String json = JsonSchema.toJson(userValidator.description());
```

The output follows JSON Schema draft 2020-12:

```json
{
  "$schema": "https://json-schema.org/draft/2020-12/schema",
  "type": "object",
  "properties": {
    "email": { "type": "string", "minLength": 1, "format": "email" },
    "nickname": { "type": ["string", "null"], "minLength": 1 },
    "age": { "type": ["integer", "null"], "minimum": 0, "default": 20 },
    "tags": { "type": ["array", "null"], "items": { "type": "string", "minLength": 1 }, "default": [] }
  },
  "required": ["email"]
}
```

* A property is `required` unless it accepts an absent key. A property with `presence()` is never `required`.
* A property that accepts `null` lists `null` in its type, and a `defaultValue(...)` or `recover(...)` is written as `default`.
* A required value whose constraints accept `null` is described with the constraint `object.notNull`.
* A validator that rejects unknown properties is written with `additionalProperties: false`, and one that reads the rest with the schema of its values.
* The constraints of a list or a map are written as `minItems`, `maxItems`, `uniqueItems`, `minProperties` and `maxProperties`.
* A withheld property is `writeOnly`.
* The alternatives of a discriminated union are an `AnyOf` whose `discriminator` is the name of the key that selects one.

The generated schema describes the input of the validator. It is not a schema of the object that the validator creates, so it has the key and type of a property before `map`.

## Recursive and shared definitions

A recursive structure is described with a `ValueDescription.Reference` where it contains itself. It is written as `$ref`, to `#` for the described validator itself, and otherwise to `$defs` under the name given to `ValueValidator.lazy(name, ...)` or `ValueValidator.recursive(name, ...)`:

```java
ObjectInputValidator<Comment> commentValidator = ValueValidator.recursive("comment", self -> Yavi.schema()
        ._string("body", c -> c.notBlank())
        ._list("replies", self).defaultValue(List.of())
        .fromMap(Comment::new));

JsonSchema.toJson(commentValidator.description());
// {"$defs":{"comment":{...}},"$ref":"#/$defs/comment"}
```

A reference to the described validator itself is written as `#`. A name given to `lazy` or `recursive` is used for a definition that is referred to from more than one place.

## Limitations

* A lambda and the result of `ValueValidator.compose` are unknown. Describe them with `describedAs(description)`.
* Conditional constraints and `constraintOnTarget` rules are not described. They are not part of the shape of the input, or they span several properties.
* A constraint without a JSON Schema keyword is omitted. For example, `unique(key)` has no keyword and is not written; `unique()` is written as `uniqueItems`.
* A bean `Validator` built with `ValidatorBuilder` is not described. Use `Yavi.schema()` for the input and the classic validator for the object.
* A `renaming` view and an `including` or `excluding` view are not part of the description of the validator. They write an object; the description still describes the input.
* A description reflects what the validator checks. It does not replace validation: a client that trusts the schema still needs the validator on the server.


---

# FILE: references/getting-started.md

# Getting Started

Welcome to YAVI. This page adds the dependency, writes the first schema and validates an input.

> This content is derived from https://hibernate.org/validator/documentation/getting-started/

## Prerequisites

* Java 21 or later. YAVI 0.18 is compiled for Java 21.
* Apache Maven, or an equivalent Gradle setup.

## Project setup

Add YAVI to `pom.xml`:

```xml
<dependency>
    <groupId>am.ik.yavi</groupId>
    <artifactId>yavi</artifactId>
    <version>0.18.0</version>
</dependency>
```

## Choosing a style

YAVI validates in two styles. Choose by what is available when validation starts:

| You have | You want | Use |
| --- | --- | --- |
| Input that is not an object yet: a `Map`, a parsed JSON document, request parameters | To validate it and create the object, so that an invalid object never exists | `Yavi.schema()` with `fromMap(f)` |
| An object that is already created, as with Bean Validation | To check the object and get its violations | `ValidatorBuilder` |

The rest of this page describes the first style. The classic style is shown at the end.

## Defining a schema

`Yavi.schema()` describes the properties of the input. Each property method gives the type, the name and the constraints, and `fromMap` ends the schema with a validator that reads those properties from a `Map<String, Object>` and calls a constructor.

```java
package com.example;

import am.ik.yavi.input.ObjectInputValidator;
import am.ik.yavi.validator.Yavi;

public record Car(String manufacturer, String licensePlate, Integer seatCount) {
    public static final ObjectInputValidator<Car> validator = Yavi.schema()
            ._string("manufacturer")
            ._string("licensePlate", c -> c.greaterThanOrEqual(2).lessThanOrEqual(14))
            ._integer("seatCount", c -> c.greaterThanOrEqual(2))
            .fromMap(Car::new);
}
```

The schema states that:

* `manufacturer` must be a string,
* `licensePlate` must be a string of 2 to 14 characters,
* `seatCount` must be an integer of at least 2.

A property is required. An absent key is reported with `object.required`, and `null` with `object.notNull`, so no `notNull()` is needed and `Car::new` is never given `null`. A property that may be `null` says so with `nullable()` or `optional()`, as described in [Optional and Default Values](optional-and-defaults.md).

## Validating input

Give a map to the validator.

> Note: a Zod-style API would call this `parse` or `safeParse`. YAVI keeps `validate` and `validated` for backward compatibility with the 0.17 API. `validate` checks the input and returns a `Validated`, so it plays the role of `safeParse`.

The following program is complete. Press the **Run** button below it to compile and execute the program in your browser; the output appears under the program. The first run downloads the WebAssembly runtime and can take several seconds, so the page may appear idle for a while. Later runs are faster.

The input leaves out `manufacturer`, so the first run reports the missing property. The cell is editable: add `"manufacturer", "yavi"` to the `Map` and press **Run** again. The program then prints the created `Car` (`valid: Car[manufacturer=yavi, ...]`).

```java runnable
import java.util.Map;

import am.ik.yavi.core.ConstraintViolations;
import am.ik.yavi.core.Validated;
import am.ik.yavi.input.ObjectInputValidator;
import am.ik.yavi.validator.Yavi;

public class Main {

    record Car(String manufacturer, String licensePlate, Integer seatCount) {
    }

    static final ObjectInputValidator<Car> validator = Yavi.schema()
            ._string("manufacturer")
            ._string("licensePlate", c -> c.greaterThanOrEqual(2).lessThanOrEqual(14))
            ._integer("seatCount", c -> c.greaterThanOrEqual(2))
            .fromMap(Car::new);

    public static void main(String[] args) {
        switch (validator.validate(Map.of("licensePlate", "DD-AB-123", "seatCount", 4))) {
            case Validated.Valid<Car>(Car car) -> System.out.println("valid: " + car);
            case Validated.Invalid<Car>(ConstraintViolations violations) -> {
                System.out.println("invalid");
                System.out.println(violations.size());
                System.out.println(violations.get(0).message());
            }
        }
    }
}
```
<!-- run: expected output
invalid
1
"manufacturer" is required
-->

A value that does not represent the type of its property is reported with `object.type`, for example `"seatCount" must be of type integer` for the string `"four"`. No exception is thrown for a malformed input.

## Handling the result

`validate` returns a `Validated<Car>`, which holds either the `Car` or the `ConstraintViolations`. Every violation is accumulated, so an invalid input reports every failed rule at once. `Validated` is a sealed interface, so an exhaustive `switch` with record deconstruction handles both cases and the compiler checks that neither is forgotten:

```java
switch (Car.validator.validate(map)) {
    case Validated.Valid<Car>(Car car) -> save(car);
    case Validated.Invalid<Car>(ConstraintViolations violations) ->
        violations.forEach(violation -> report(violation.name(), violation.message()));
}
```

When the caller wants the object or an exception, `validated(map)` returns the `Car` itself and throws a `ConstraintViolationsException` if the input is invalid. `violations.messagesByName()` returns the messages grouped by property, and `violations.details()` returns records that a JSON library serializes for an API response. See [Handling Results](result-handling.md) and [Violations](violations.md).

## The same schema on another input

The schema is not tied to a `Map`. The same validator reads a JSON tree with `readingWith(reader)`, request parameters with `readingParameters()`, and typed arguments with `apply(f)` instead of `fromMap(f)`. See [JSON Trees](input-json.md), [Request Parameters and Forms](input-parameters.md) and [Typed Arguments](input-arguments.md).

## Validating an object that already exists (classic API)

When the object already exists, declare the constraints on its properties with `ValidatorBuilder`. The classic API returns `ConstraintViolations` for an instance:

```java
package com.example;

import am.ik.yavi.builder.ValidatorBuilder;
import am.ik.yavi.core.ConstraintViolations;
import am.ik.yavi.core.Validator;

public class CarValidation {

    record Car(String manufacturer, String licensePlate, Integer seatCount) {
    }

    static final Validator<Car> validator = ValidatorBuilder.<Car>of()
            .constraint(Car::manufacturer, "manufacturer", c -> c.notNull())
            .constraint(Car::licensePlate, "licensePlate", c -> c.notNull().greaterThanOrEqual(2).lessThanOrEqual(14))
            .constraint(Car::seatCount, "seatCount", c -> c.greaterThanOrEqual(2))
            .build();

    public static void main(String[] args) {
        ConstraintViolations violations = validator.validate(new Car(null, "D", 1));
        System.out.println(violations.size()); // 3
        System.out.println(violations.get(0).message()); // "manufacturer" must not be null
    }
}
```

`ValidatorBuilder.constraint` applies the constraints to the value returned by a getter of the `Car` instance. Unlike a schema property, a value that is `null` is valid unless a constraint such as `notNull()` rejects it. See [Object Validation](using-yavi.md).

## Next steps

* [Core Concepts](concepts.md) explains the pipeline behind these calls.
* [Defining a Schema](defining-a-schema.md) lists the property methods and constraints.
* [Optional and Default Values](optional-and-defaults.md) covers absent keys, `null` and defaults.
* [Objects and Collections](objects-and-collections.md) covers nested objects, lists and maps.


---

# FILE: references/index.md

# Overview

YAVI (pronounced jɑ-vάɪ) stands for *Yet Another ValIdation*. Since 0.18 it gives Java a Zod-like way to describe and validate input. Since 0.18 a schema written in code reads untyped input and either creates a typed object or reports every violation with its location. The same idea is found in [Zod](https://zod.dev) for TypeScript and in [Raoh](https://github.com/raoh-project/raoh-java) for Java; [Comparison with Zod](coming-from-zod.md) maps the two APIs.

[View the project on GitHub](https://github.com/making/yavi)

## Design principles

* Input-first. An input is described once and read from typed arguments, a map, a JSON tree or request parameters. The object is created only when every property is valid.
* Type safety by construction. Required and nullable values have different Java types, so NullAway and the Kotlin compiler can check the use of a validated value. `Validated` is sealed, and a reversible validator is checked at compile time.
* No reflection. A property is read by a method reference, not by inspecting a class.
* No runtime annotations. Constraints are written as Java code, so the compiler checks them.
* No required runtime dependency. YAVI's JSpecify annotations are `provided`, so they are not transitive and an application runs with only the YAVI jar on its classpath. Add `org.jspecify:jspecify` to compile code that declares `@Nullable`, or to run a nullness checker such as NullAway; static null checking is recommended, not required.
* Staged builders. A modifier that has no effect, such as `.nullable().optional()`, does not compile.

The classic `ValidatorBuilder` remains for objects that already exist, but the schema-first API is the recommended starting point.

## What 0.18 adds

YAVI 0.18 is compiled for Java 21 and adds a schema-first API:

* `Yavi.schema()` describes an input once and reads it from a `Map`, a JSON tree, request parameters or typed arguments.
* `fromMap(f)` creates the object only when every property is valid, so an invalid object never exists.
* Properties can be nested objects, lists, maps, unions and structures that contain themselves.
* A validated property can be mapped to a value object and written back with a reversible schema.
* Rules that span several properties are written with `constraintOnTarget` and fallible factories.
* `description()` and `JsonSchema` describe the input, for documentation and client generation.

The classic `ValidatorBuilder` API remains available for objects that already exist. See [Migration from 0.17](migration-0.17-to-0.18.md) for the changes between the releases.

## Who this is for

This documentation is for developers who receive input they do not control, such as a JSON request body, a submitted form or a row read from a database, and who want a typed object or a complete list of violations in return. It assumes Java 21 and a working Maven or Gradle build.

Readers coming from Zod or Raoh can start with [Comparison with Zod](coming-from-zod.md). Bean Validation solves the different problem of checking an object that already exists; that model is supported through `ValidatorBuilder` and described in [Object Validation](using-yavi.md).

## Documentation map

* Getting Started
  * [Introduction](introduction.md): the validation models and the guarantees of the library.
  * [Getting Started](getting-started.md): the dependency, the first schema and the result.
  * [Core Concepts](concepts.md): input, schemas, `Validated`, violations and nullness.
* Schemas
  * [Defining a Schema](defining-a-schema.md): properties, constraints, names and transforms.
  * [Optional and Default Values](optional-and-defaults.md): absent keys, `null`, defaults and recovery.
  * [Value Objects and Transforms](value-objects.md): mapping a value to a domain type.
  * [Objects and Collections](objects-and-collections.md): nested objects, lists, maps, embedding and recursion.
  * [Unions](unions.md): alternatives and discriminated unions.
  * [Cross-Field Rules](cross-field-rules.md): rules over several properties and fallible factories.
  * [Describing a Schema](describing-a-schema.md): descriptions and JSON Schema.
* Inputs and results
  * [Maps and Untyped Values](input-maps.md), [JSON Trees](input-json.md), [Request Parameters and Forms](input-parameters.md), [Typed Arguments](input-arguments.md).
  * [Handling Results](result-handling.md), [Violations](violations.md), [Messages and Localization](messages.md).
  * [Writing an Object Back](writing-back.md): reversible schemas.
* Reference
  * [Built-in Constraints](built-in-constraints.md) lists every constraint.
  * [Object Validation](using-yavi.md) covers the classic `ValidatorBuilder` API.
  * [Comparison with Bean Validation](coming-from-bean-validation.md) maps the annotations to YAVI constraints.


---

# FILE: references/input-arguments.md

# Typed Arguments

`apply(f)` ends a schema with a validator of typed arguments, for values that are already bound to their types. The result is an `ArgumentsNValidator` that is called with the arguments and creates the object only when every argument is valid.

```java
Arguments3Validator<String, String, Integer, Car> carValidator = Yavi.schema()
        ._string("manufacturer", c -> c.notBlank())
        ._string("licensePlate", c -> c.greaterThanOrEqual(2).lessThanOrEqual(14))
        ._integer("seatCount", c -> c.greaterThanOrEqual(2))
        .apply(Car::new);

Validated<Car> validated = carValidator.validate("Morris", "DD-AB-123", 4);
```

## Ending a schema with apply

The properties are declared as for `fromMap`, with the same constraints and staged types. Their names are used in the violations, in `description()` and in the JSON Schema, as they are when the object is read from a map.

* Each argument has its own name: `apply` and `flatApply` throw an `IllegalArgumentException` when two arguments have the same name.
* All violations are accumulated, so an invalid call reports every failed constraint at once.
* A `null` argument is validated as `null`; there is no absent state. `nullable()` changes the type of the argument to `@Nullable`.
* `validated(...)` returns the object and throws a `ConstraintViolationsException` for an invalid call.
* The validator is immutable and thread-safe.

## Flat creation

`flatApply(f)` takes a function that returns a `Validated` and can fail, for example a factory method of the domain:

```java
Arguments2Validator<LocalDate, LocalDate, DateRange> validator = Yavi.schema()
        ._localDate("start")
        ._localDate("end")
        .flatApply(DateRange::of);
```

The function is applied only when every argument is valid. It is given neither the locale of the validation nor the violated value; the violations it returns are reported with the locale of the validation. `Validated.failureWith(ViolationMessage.of("dateRange.invalid", "start must be before end"))` is the way to fail.

## Relation to fromMap

`fromMap` and `apply` describe the same properties. The difference is the input:

| Input | Ending | Type |
| --- | --- | --- |
| A `Map<String, Object>`, a JSON tree, request parameters | `fromMap(f)` | `ObjectInputValidator<X>` |
| Values that already have their types | `apply(f)` | `ArgumentsNValidator<A1, ..., AN, X>` |

Use `apply` when the caller already has the values as Java objects, such as a method that takes several parameters, and `fromMap` when the input is untyped. The same schema cannot be used with both endings at once; build two validators from the same property definitions.

## Embedded and rest arguments

An argument added with `_embedded` is a `Map<String, Object>` validated by the given validator, and one added with `_rest` is a map of the keys that no other argument is defined for. In both cases the function given to `apply` receives the validated map:

```java
Arguments2Validator<Map<String, Object>, Map<String, String>, Account> validator = Yavi.schema()
        ._embedded(userNameValidator)
        ._rest(Yavi._string(c -> c.notBlank()))
        .apply(Account::new);
```

An `_embedded` validator with `optional()`, `nullable()` or `defaultValue(...)` is given `null` when none of its properties has a value. `_rest` is the last argument.

## Arity and ObjectInputValidator.of

A schema has at most 16 arguments. Embedding is the way to read more keys: `_embedded` adds the properties of another validator, and the same map is read.

When the arguments are built dynamically, use `ObjectInputValidator.of(parts, mapper)`. A part is `Part.Property(name, validator)`, `Part.Embedded(validator)` or `Part.Rest(validator)`, and the mapper receives the validated values in the order of the parts:

```java
ObjectInputValidator<Pair> validator = ObjectInputValidator.of(List.of(
        new ObjectInputValidator.Part.Property<>("first", Yavi._string("first", c -> c.notBlank()).untyped()),
        new ObjectInputValidator.Part.Property<>("second", Yavi._string("second", c -> c.notBlank()).untyped())),
        values -> new Pair((String) values.get(0), (String) values.get(1)));
```

`ObjectInputValidator.ofReversible(parts, mapper)` takes `ReversiblePart`s, a part with its reverse and its accessor, and produces a validator that also writes the object back.


---

# FILE: references/input-json.md

# JSON Trees

A schema reads the tree model of a JSON library as it is, without copying it to a map. `readingWith(reader)` binds a validator to an `InputReader`, which tells how to read the nodes of the tree, and `from(reader, f)` on the schema builds such a validator.

```java
ValueValidator<JsonNode, User> nodeValidator = Yavi.schema()
        ._string("email", c -> c.notBlank().email())
        ._integer("age", c -> c.greaterThanOrEqual(0))
        ._object("address", addressValidator)
        .from(JsonNodeReader.INSTANCE, User::new);
```

YAVI has no dependency on a JSON library. A reader is a small stateless class written once per tree model and shared by every validator, and the rules and violations are those of a map.

## Implementing an input reader

Implement `CoercibleInputReader` of the node type. [Jackson](integrations-jackson.md#jsonnodereader) shows a complete reader for its `JsonNode`; the methods it implements are:

| Method | What it returns |
| --- | --- |
| `isNull(node)` | Whether the node is validated like `null` |
| `value(node)` | A scalar as a JDK type; any other node as it is |
| `isObject(node)`, `property(object, name)`, `properties(object)` | The properties of an object |
| `isArray(node)`, `elements(array)` | The elements of an array |
| `value(node, type)` | The value before it is checked as `type`; override it to read a format of your own |

The reader applies to nested validators too, so a nested validator is built with `fromMap` whatever input is read in the end, and a validator of maps also reads nodes: `mapValidator.readingWith(reader)`.

A reader returns a number as the tree holds it. A validator cannot recover what the parser dropped.

## The JDK JSON API (JEP 540)

The JDK incubates a JSON API, [JEP 540](https://openjdk.org/jeps/540) in JDK 28. It provides a tree model of its own, so a reader can be written without a JSON library:

```java
@Override
public Object value(JsonValue node) {
    return switch (node) {
        case JsonString string -> string.asString();
        case JsonNumber number -> new BigDecimal(number.toString()); // the text of the number, so that no digit is lost
        case JsonBoolean bool -> bool.asBoolean();
        default -> node;
    };
}
```

The other methods use `JsonObject.asMap()` and `JsonArray.asList()`. YAVI's test suite contains the complete implementation, [`JdkJsonReader.java`](https://github.com/making/yavi/blob/7cd63eb24c23b2569e67f0a3e4f8ea1b83adc38e/src/test/java28/am/ik/yavi/input/JdkJsonReader.java). It lives in a separate source root (`src/test/java28`) because the module is an incubator of JDK 28; on an earlier JDK, use the Jackson reader above.

## Coercing strings

A tree whose scalars are all strings, such as a JSON document whose numbers are sent as strings, is read with `coercingStrings()` of its reader:

```java
ValueValidator<JsonNode, User> validator = userValidator
        .readingWith(JsonNodeReader.INSTANCE.coercingStrings());

ValueValidator<Object, Integer> page = Yavi._integer("page", c -> c.greaterThanOrEqual(1))
        .readingWith(InputReader.ofJdkTypes().coercingStrings());
```

The strings are taken as text that stands for a value, by the rules of [Request Parameters and Forms](input-parameters.md#coercion-and-stringcoercion). `StringCoercion.strict().trimming().booleanWords()` relaxes them for text written by a person. A reader that coerces strings is an `InputReader` only, so the rules are given once, and no text is coerced twice.

## Limits and fidelity

* A reader is a view of the tree: nested objects, arrays and the keys of a map are read from the nodes, and `_embedded` reads the same node as the properties.
* The parser's limits apply before validation: a depth limit, the maximum number of digits and strict duplicate detection are configured on the parser; see [Jackson](integrations-jackson.md#mapper-settings).
* A number that no target type holds is reported with `object.type`, never with an exception.
* An absent property and a `null` node are different: `isNull` is for the latter, and an absent property is told by `property(object, name)` returning `null`.
* A violation holds the value as the reader returned it, not the node.
* The tree of a JSON library is read, not written. Use [Writing an Object Back](writing-back.md) for output.


---

# FILE: references/input-maps.md

# Maps and Untyped Values

`fromMap` ends a schema with a validator that reads a `Map<String, Object>`, such as a parsed JSON object, by the names of its properties. No cast and no reflection are involved, and the object is created only when every property is valid.

```java
record User(String email, Integer age, Role role) {}

ObjectInputValidator<User> userValidator = Yavi.schema()
        ._string("email", c -> c.notBlank().email())
        ._integer("age", c -> c.greaterThanOrEqual(0))
        ._enum("role", Role.class)
        .fromMap(User::new);

Validated<User> validated = userValidator.validate(Map.of(
        "email", "jd@example.com", "age", 30, "role", "ADMIN"));
```

The following complete program validates a map into a `User` and prints either the created object or every violation's name and message.

```java runnable
import java.util.Map;

import am.ik.yavi.core.ConstraintViolations;
import am.ik.yavi.core.Validated;
import am.ik.yavi.input.ObjectInputValidator;
import am.ik.yavi.validator.Yavi;

public class Main {

    record User(String email, Integer age) {
    }

    static final ObjectInputValidator<User> validator = Yavi.schema()
            ._string("email", c -> c.notBlank().email())
            ._integer("age", c -> c.greaterThanOrEqual(0))
            .fromMap(User::new);

    public static void main(String[] args) {
        for (Map<String, Object> input : java.util.List.<Map<String, Object>>of(
                Map.of("email", "jd@example.com", "age", 30),
                Map.of("email", "not-an-email", "age", -1))) {
            switch (validator.validate(input)) {
                case Validated.Valid<User>(User user) -> System.out.println("valid: " + user);
                case Validated.Invalid<User>(ConstraintViolations violations) -> violations
                    .forEach(v -> System.out.println(v.name() + ": " + v.message()));
            }
        }
    }

}
```
<!-- run: expected output
valid: User[email=jd@example.com, age=30]
email: "email" must be a valid email address
age: "age" must be greater than or equal to 0
-->

## Reading an object from a map

The values are checked against the type of their property:

* A value that does not represent the type is reported with `object.type`: `"age" must be of type integer`. Nothing is coerced, so `"30"` is not a number in a map. Use [request parameters](input-parameters.md) for text.
* A number whose value is kept is accepted whatever its Java type is: `30L` and `30.0` are an `Integer`, `30.5` is not.
* An enum constant is read from its name, a temporal value, a `Duration` and a `Period` from their ISO-8601 string, a `UUID` and a `URI` from their string form: `_object("id", UUID.class)`.
* An absent key is validated like `null`. A property is required unless `optional()`, `nullable()` or `defaultValue(...)` says otherwise; the absent key is reported with `object.required` and an explicit `null` with `object.notNull`.
* A key that no property is defined for is ignored. `rejectingUnknownProperties()` reports it with `object.unknownProperty`, on that map only.
* A map with a key that is not a string is reported with `object.type`.

```java
ObjectInputValidator<User> strict = userValidator
        .rejectingUnknownProperties();
strict.validate(Map.of("email", "jd@example.com", "age", 30, "role", "ADMIN", "admin", true));
// "admin" is not a known property
```

## The type of a property

Some properties need their type to read the input. `_enum(name, type)` and `_object(name, type)` take it; without it the schema cannot be used for a map:

```java
._enum("role", Role.class)
._object("id", UUID.class)
```

`ignoringCase()` of an enum validator reads a constant in any case: `._enum(Yavi._enum("role", Role.class).ignoringCase())`.

## Validating a value that is not a property

`Yavi._string`, `Yavi._integer` and the other validators of a single value validate a value by themselves. A validator without a name is the element of a list, the value of a map or an alternative of `anyOf`, and its violations are named by the place where it is used (`roles[0]`). Validated on its own, it has the empty name and the message says "The value" in place of the name.

```java
StringValidator<String> tag = Yavi._string(c -> c.notBlank().lessThanOrEqual(10));
tag.validate("").errors().get(0).message(); // The value must not be blank
```

## Combining validators of unknown type

`untyped()` turns any validator that knows its input type into a `ValueValidator<Object, X>`, for example to validate the root of a document or to combine alternatives of different types:

```java
ValueValidator<Object, Object> id = ValueValidator.anyOf(
        Yavi._string(c -> c.notBlank()).untyped(),
        Yavi._integer(c -> c.positive()).untyped());
```

Give the type of a lambda with `untyped(type)`, because a lambda does not know its input type. The reader that coerces strings is described in [JSON Trees](input-json.md#coercing-strings).

## When the input type must be known

The input type must be known when the validator is built. `fromMap` and `untyped()` throw an `UnsupportedOperationException` for a validator whose input type is unknown: a lambda, or an `_enum` / `_object` property added without its type. Give it with `untyped(type)`, `_enum(name, type)` or `_object(name, type)`.

`readingWith(reader)` of a validator of unknown type is accepted only for a reader of JDK types. Give the type first if the input is a node of a tree model.

The type of a property and the type of the created object are checked by the compiler. A `fromMap(User::new)` whose parameter types do not match the validated values does not compile, including the nullness of a `nullable()` argument.


---

# FILE: references/input-parameters.md

# Request Parameters and Forms

`readingParameters()` reads a flat map of strings, as a servlet request or a submitted form provides it, with the schema that reads a map or a JSON document. A string is text that stands for a value of the type of its property, and a key is the path of a nested value.

```java
record SearchForm(String q, Integer page, Boolean includeArchived, @Nullable LocalDate since, List<String> tags,
        @Nullable Address address) {}

ValueValidator<Map<String, ?>, SearchForm> searchFormValidator = Yavi.schema()
        ._string("q", c -> c.notBlank())
        ._integer("page", c -> c.greaterThanOrEqual(1)).defaultValue(1)
        ._boolean("includeArchived").defaultValue(false)
        ._localDate("since").nullable()
        ._list("tags", Yavi._string(c -> c.notBlank())).defaultValue(List.of())
        ._object("address", addressValidator).nullable()
        .fromMap(SearchForm::new)
        .readingParameters();

// ?q=yavi&page=2&since=&tags=a&tags=b&address.city=Tokyo
Validated<SearchForm> validated = searchFormValidator.validate(params);
```

Every form of such a map is accepted: a `Map<String, String>`, a `Map<String, List<String>>` such as Spring's `MultiValueMap`, and the `Map<String, String[]>` of the Servlet API. The type is `ValueValidator<Map<String, ?>, X>` whatever it is assigned to.

## Keys and paths

* `address.city` and `address[city]` are the property `city` of the object `address`; `tags[]` is `tags`.
* A key with several values is a list (`tags=a&tags=b`). Several values for a scalar property are reported with `object.type`; none is picked.
* Keys with indexes are a list in the order of the indexes: `items[0].name=pen&items[1].name=ink`.
* A skipped index is an element that is `null`, so a violation keeps the index it was sent with (`items[2].name`).
* A name that holds a dot is written in brackets (`scores[a.b]`).
* A key that has both values and nested keys (`a=1&a.b=2`) is reported with `object.type`, and a key that is not written as a path (`a..b`, `a[0`) matches no property.
* With `rejectingUnknownProperties()`, an unknown key is reported by the validator of the object that has it (`address.zip`).

## Coercion and StringCoercion

The rules are strict by default:

* A number is a decimal number in the grammar of `new BigDecimal(String)`: an optional sign, digits, an optional fraction and an optional exponent, without surrounding white space or grouping separators. `"30"` and `"30.0"` are an `Integer`; `"30.5"`, `" 30"` and `"1,000"` are not.
* A boolean is `"true"` or `"false"`.
* A string that does not stand for the type is reported with `object.type` (`"page" must be of type integer`), never with an exception. Nothing is converted to a string.

`StringCoercion` relaxes the rules for text written by a person, such as the fields of a form:

```java
StringCoercion form = StringCoercion.strict().trimming().booleanWords();

ValueValidator<Map<String, ?>, Signup> signupValidator = Yavi.schema()
        ._integer("age")
        ._boolean("subscribed").defaultValue(false) // an unchecked checkbox sends nothing
        .fromMap(Signup::new)
        .readingParameters(form);

signupValidator.validate(Map.of("age", " 30 ", "subscribed", "on")); // Signup[age=30, subscribed=true]
```

* `trimming()` reads every text without its surrounding white space, whatever its property is, and validates a blank string like `null`. The constraints see the trimmed text.
* `booleanWords()` takes `true`, `1`, `yes`, `on` and `false`, `0`, `no`, `off` in any case. `booleanWords(trueWords, falseWords)` takes the words of the application instead.
* A `String` whose white space is part of it, such as a password, says so with `untrimmed()` of its validator: `._string(Yavi._string("password", c -> c.greaterThanOrEqual(8)).untrimmed())`.
* Each rule is given once: `reader.coercingStrings(rules).coercingStrings()` and `booleanWords(...).booleanWords()` do not compile.
* A validator reads with the last reader it is given: `readingWith(reader)` after `readingParameters()` coerces no string.

## Empty values and defaults

* An empty string is validated like `null`, whatever the type of its property is. `optional()`, `nullable()` and `defaultValue(...)` apply to it. Give `defaultValue("")` to a string property that must receive `""`.
* Text has no `null`, so a property that would reject an empty string with `object.notNull` reports `object.required` (`"page" is required`), as it does for an absent key. The violation of a constraint that rejects `null`, such as `notBlank()`, is reported as it is.
* An empty list or object cannot be sent: its key is absent, which is validated like `null`. Give `defaultValue(List.of())` to a list that may be empty, such as checkboxes.
* `recover` suits a parameter that must not fail a request: `._integer("size", c -> c.greaterThanOrEqual(1).lessThanOrEqual(100)).recover(20)`.

## Labels and messages

A form calls a field by its label. `label` changes `{0}` of every message of the property and of its elements; the name, the path and the pointer of a violation are unchanged. `typeMessage` replaces the message of `object.type`, and `required` the message of `object.required`.

```java
record Token(String name, Integer ttl, List<String> roles) {}

ValueValidator<Map<String, ?>, Token> tokenValidator = Yavi.schema()
        ._string("name", c -> c.notBlank()).label("Token name")
        ._integer("ttl", c -> c.positive()).typeMessage("\"{0}\" must be a number of seconds")
        ._list("roles", Yavi._string(c -> c.notBlank())).label("Roles").required("Select at least one role")
        .fromMap(Token::new)
        .readingParameters()
        .formattingWith(new MessageSourceMessageFormatter(messageSource::getMessage));
```

See [Messages and Localization](messages.md) for the formatter and the rule about messages written in code.

## A list in one parameter

`splitBy` after `_list` reads one parameter as a list: `?tags=java,yavi`, `?ids=1,2,3`, or one URI per line of a `textarea`.

```java
ValueValidator<Map<String, ?>, Article> articleValidator = Yavi.schema()
        ._string("title", c -> c.notBlank())
        ._list("tags", Yavi._string(c -> c.notBlank().lessThanOrEqual(10)), c -> c.unique()).splitBy(",")
        ._list("related", Yavi._integer(c -> c.positive())).splitBy(",").defaultValue(List.of())
        ._list("links", Yavi._object(URI.class)).splitBy(Pattern.compile("\\R")).defaultValue(List.of())
        .fromMap(Article::new)
        .readingParameters();
```

* The separator is a text taken literally or a `Pattern`. The elements are text that stands for a value, and their violations are located under their index (`tags[1]`).
* Every text is split, also the values of a repeated key: `tags=a,b&tags=c` is `[a, b, c]`.
* No element is dropped or trimmed. `a,,b` has three elements, and the second has no value. A separator at the end starts no element: `a,b,` is `[a, b]`.
* An empty parameter (`tags=`) has no value.
* `splitBy` is written after `_list`, before the other modifiers; only `label` and `typeMessage` may be written before it.
* A value that is neither text nor a list is reported with `object.type` (`"tags" must be of type array or string`), not taken for a list of one element.

## Limits and security

* An index is at most 255 (`ParameterTree.DEFAULT_MAX_INDEX`). A greater number is a name, so `tags[999999999]` is reported with `object.type` and allocates nothing.
* `ParameterTree.of(map, maxIndex)` gives another limit. Give the same limit to the reader if the validator reads a tree with another one.
* A skipped index is an element that is `null`; the list has the length of the largest index sent, so the limit bounds what an untrusted request can allocate.
* A key that is not a path matches no property and is ignored, or reported by `rejectingUnknownProperties()`.
* `readingParameters()` validates the `ParameterTree` of the map, which any validator reads with `readingWith(ParameterTree.reader())`.

## Writing parameters back

A form that is not valid is shown again with the text that was sent, without copying the fields by hand. `ParameterTree` returns the parameters in the shape of the schema, and the same call gives the empty form for a request that lacks a parameter. See [Writing an Object Back](writing-back.md#parameters-and-forms).


---

# FILE: references/integrations-jackson.md

# Jackson

A JSON document is read with a schema in two steps: the parser creates a tree, and an `InputReader` tells the validator how to read its nodes. YAVI does not depend on Jackson; the reader below is the only code that mentions it.

## JsonNodeReader

```java
import java.util.Map;

import am.ik.yavi.core.CoercibleInputReader;
import org.jspecify.annotations.Nullable;
import tools.jackson.databind.JsonNode;

public final class JsonNodeReader implements CoercibleInputReader<JsonNode> {

    public static final JsonNodeReader INSTANCE = new JsonNodeReader();

    @Override
    public boolean isNull(JsonNode node) {
        return node.isNull() || node.isMissingNode();
    }

    @Override
    public Object value(JsonNode node) { // a scalar as a JDK type
        if (node.isString()) {
            return node.stringValue();
        }
        if (node.isNumber()) {
            return node.numberValue();
        }
        if (node.isBoolean()) {
            return node.booleanValue();
        }
        return node;
    }

    @Override
    public boolean isObject(JsonNode node) {
        return node.isObject();
    }

    @Override
    public @Nullable JsonNode property(JsonNode object, String name) {
        return object.get(name); // null if absent
    }

    @Override
    public Iterable<Map.Entry<String, JsonNode>> properties(JsonNode object) {
        return object.properties();
    }

    @Override
    public boolean isArray(JsonNode node) {
        return node.isArray();
    }

    @Override
    public Iterable<JsonNode> elements(JsonNode array) {
        return array;
    }

}
```

The class uses Jackson 3 (`tools.jackson.databind.JsonNode`). Build the validator with `from(JsonNodeReader.INSTANCE, User::new)`, or bind a validator of maps with `readingWith(JsonNodeReader.INSTANCE)`. The reader applies to nested validators too.

For a document whose scalars are all strings, use `JsonNodeReader.INSTANCE.coercingStrings()`; see [Coercing strings](input-json.md#coercing-strings).

## Mapper settings

The mapper decides what the reader sees. A default `JsonMapper` holds a number with a fraction as a `double` and keeps the last of a key written twice. Configure it before parsing:

```java
JsonMapper jsonMapper = JsonMapper.builder()
        .enable(DeserializationFeature.USE_BIG_DECIMAL_FOR_FLOATS) // 0.10 is the BigDecimal 0.10
        .enable(StreamReadFeature.STRICT_DUPLICATE_DETECTION) // {"role": "user", "role": "admin"} is refused
        .build();
```

The imports are `tools.jackson.databind.json.JsonMapper`, `tools.jackson.databind.DeserializationFeature` and `tools.jackson.core.StreamReadFeature`.

In Spring Boot 4, the auto-configured `JsonMapper` takes the same features from `application.properties`:

```properties
spring.jackson.deserialization.use-big-decimal-for-floats=true
spring.jackson.read.strict-duplicate-detection=true
```

The property names follow the Jackson features, so no builder is needed.

The same settings apply to `readValue(json, Map.class)` when the validator reads a map instead of a tree.

## Duplicate keys and number fidelity

| JSON | Read by a default mapper |
| --- | --- |
| `0.10` | `_bigDecimal` receives `0.1`; the scale is lost |
| `12345678901234567.89` | `_bigDecimal` receives `12345678901234568`; 17 digits are kept |
| `19.990000000000000000001` | `_bigDecimal` receives `19.99`, which `fractionDigits(2)` accepts |
| `1e400` | `_double` receives `Infinity`; `_bigDecimal` reports `object.type` |
| `{"role": "user", "role": "admin"}` | `role` is `admin` |

With `USE_BIG_DECIMAL_FOR_FLOATS`, `_bigDecimal` receives every digit and the scale, and `_double` and `_float` round the number once. With `STRICT_DUPLICATE_DETECTION`, a document with a duplicated key is refused by the parser with a `JacksonException`, before validation.

A number that no target type holds is reported with `object.type`, never with an exception. A parser limit, such as a depth limit, applies before the validator.

## Serializing violations

`violations.details()` returns records that a JSON library serializes as they are:

```java
@PostMapping("/users")
ResponseEntity<?> create(@RequestBody Map<String, Object> request) {
    return switch (userValidator.validate(request)) {
        case Validated.Valid<User>(User user) ->
            ResponseEntity.ok(userService.create(user));
        case Validated.Invalid<User>(ConstraintViolations violations) ->
            ResponseEntity.badRequest().body(violations.details());
    };
}
```

```json
[{"name": "items[1].quantity", "pointer": "/items/1/quantity", "messageKey": "numeric.lessThanOrEqual",
  "message": "\"items[1].quantity\" must be less than or equal to 99", "params": {"max": 99}}]
```

* `ViolationDetail` is a sealed interface of `Simple` and `NoAlternativeMatched`; `switch` over it needs no `default`.
* `params` holds the arguments by name; the violated value is not in a detail. Read `violation.violatedValue()` if the server needs it.
* `ViolationDetail` works with GraalVM native image out of the box.
* `pointer` is what the `errors[].pointer` of an RFC 9457 problem detail holds; `violation.pointer()` gives it for one violation.
* `messagesByName()` is for a form rather than a JSON response.


---

# FILE: references/integrations-kotlin.md

# Kotlin

Kotlin uses the same public API as Java. A schema is built with `Yavi.schema()`, and the nullness annotations of JSpecify are read by the Kotlin compiler, so a value that may be `null` has to be a nullable Kotlin type. The `validator<T>` DSL builds a classic `Validator`.

## Using the schema API from Kotlin

A constraint function is written with `it`, and the constructor is called with a method reference:

```kotlin
data class Member(val name: String, val nickname: String?)

val memberValidator = Yavi.schema()
    ._string("name") { it.notBlank().lessThanOrEqual(50) }
    ._string("nickname") { it.lessThanOrEqual(20) }.nullable()
    .apply(::Member)
```

`.apply(::Member)` returns an `ArgumentsNValidator`; `.fromMap(::Member)` reads a map. The Kotlin type of a parameter tells the compiler what the validator accepts, as in Java.

For a property after the first, give the constructor as a method reference (`apply(::Account)`): Kotlin cannot name the earlier argument types in the extension, so a lambda would see them as `Nothing`.

A single value validator is built with the top-level functions of `am.ik.yavi.validator`, which take the enum or object type as a type argument instead of a `Class` literal. Import them by name, and alias one of them if the functions of the same name from `am.ik.yavi.builder` are imported too:

```kotlin
import am.ik.yavi.validator._enum
import am.ik.yavi.validator._object

val role = _enum<Role>("role") { it.oneOf(Role.ADMIN) }
val id = _object<UUID>("id")
```

## The Kotlin DSL

`validator<T>` of `am.ik.yavi.builder` builds a `Validator<T>` for an object that already exists. The DSL obtains property names with Kotlin reflection, so `kotlin-reflect` must be on the runtime classpath.

```kotlin
val validator = validator<User> {
    User::name {
        notNull()
        lessThanOrEqual(20)
    }
    User::email {
        notNull()
        email()
    }
}
```

A property can be given another name, and nested objects and collections are validated with `nest` and `forEach`:

```kotlin
val validator = validator<Order> {
    (Order::customer)("Customer") {
        notNull()
    }
    Order::items forEach {
        OrderItem::name {
            notBlank()
        }
    }
    Order::customer nest {
        Customer::name {
            notBlank()
        }
    }
}
```

* `nestIfPresent` and `forEachIfPresent` validate nullable nested objects, collections, maps and arrays only when they are present.
* Temporal and enum properties have their own overloads; for example, `past()` and `oneOf(Status.ACTIVE)`.
* `onCondition` and `onGroup` add conditional and group-specific constraints, and `unwrap()` gives the underlying `ValidatorBuilder`.
* The DSL builds the classic `Validator` of [Object Validation](using-yavi.md), not the schema API. A `Validator` validates an object that exists; a schema creates it.

## Nullability

YAVI is annotated with JSpecify. A `nullable()` property is `@Nullable`, which Kotlin reads as `String?`, and a function given to `apply` or `fromMap` must declare that parameter nullable:

```kotlin
data class Member(val name: String, val nickname: String?)

val validator = Yavi.schema()
    ._string("name") { it.notBlank() }
    ._string("nickname") { it.lessThanOrEqual(20) }.nullable()
    .apply(::Member)
```

The validated type of the Kotlin DSL is not nullable: `validator<T>`, `nest` and `forEach` declare `T : Any`. Kotlin 2.1 or later reports a mismatch with the JSpecify annotations as an error; compile with `-Xjspecify-annotations=strict` to check every parameter and result.

## Coroutines

The extensions in `am.ik.yavi.fn` suspend the handling of a `Validation` result. `awaitFold`, `awaitBimap`, `awaitMap`, `awaitMapErrors` and `awaitMapError` correspond to `fold`, `bimap`, `map`, `mapErrors` and `mapError`, and require `kotlinx-coroutines-core`:

```kotlin
import am.ik.yavi.fn.awaitFold

suspend fun createUser(validated: Validated<User>): HttpStatus = validated.awaitFold(
    errorsMapper = { violations -> HttpStatus.BAD_REQUEST },
    mapper = { user -> HttpStatus.OK },
)
```


---

# FILE: references/integrations-nullaway.md

# NullAway

Since 0.18.0 the type of a validated value tells whether it can be `null`: `ValueValidator<String, String>` never succeeds with `null`, and `ValueValidator<String, @Nullable String>` may. NullAway in JSpecify mode checks this, so the compiler reports a forgotten `nullable()` before a `NullPointerException` can happen.

## JSpecify annotations

YAVI is annotated with [JSpecify](https://jspecify.dev) (`@NullMarked`, `@Nullable`). The package `am.ik.yavi.jsr305` is removed. YAVI does not bring `org.jspecify:jspecify`, so add it to your dependencies:

```xml
<dependency>
    <groupId>org.jspecify</groupId>
    <artifactId>jspecify</artifactId>
    <version>1.0.1</version>
</dependency>
```

A value that passed validation is handed over with its declared type, so the function given to `apply` needs no `@Nullable` parameter and no `Objects.requireNonNull`.

## Configuring NullAway

[`nullability-maven-plugin`](https://github.com/making/nullability-maven-plugin) configures Error Prone and NullAway, including `NullAway:JSpecifyMode` and `OnlyNullMarked`, by extending the compiler arguments of `maven-compiler-plugin`:

```xml
<plugin>
    <groupId>am.ik.maven</groupId>
    <artifactId>nullability-maven-plugin</artifactId>
    <version>0.5.2</version>
    <extensions>true</extensions>
    <executions>
        <execution>
            <goals>
                <goal>configure</goal>
                <goal>generate-package-info</goal>
            </goals>
        </execution>
    </executions>
    <configuration>
        <!-- main or tests; tests checks the test sources too -->
        <checking>tests</checking>
    </configuration>
</plugin>
```

The plugin is the source of truth for the compiler flags; do not repeat them in `maven-compiler-plugin`. `generate-package-info` writes a `package-info.java` with `@NullMarked` for each package, so a class is checked without annotating it.

For Kotlin, the compiler option `-Xjspecify-annotations=strict` reads the same annotations; the Kotlin compiler has none of the limitations below.

## Common reports and fixes

A parameter that receives a `nullable()` property must be declared `@Nullable`:

```java
record Member(String name, @Nullable String nickname) {}

Arguments2Validator<String, @Nullable String, Member> validator = Yavi.schema()
        ._string("name", c -> c.notBlank())
        ._string("nickname", c -> c.lessThanOrEqual(20)).nullable()
        .apply(Member::new);
```

```
[NullAway] parameter nickname of referenced method is @NonNull, but parameter in functional interface method am.ik.yavi.fn.Function2.apply(String,@Nullable String) is @Nullable
```

A declared validator uses the nullable type argument:

```java
ValueValidator<String, @Nullable String> memo = Yavi._string("memo", c -> c.lessThanOrEqual(100)).nullable();
```

The other parameters of the function need no `@Nullable`; only a `nullable()` property produces a nullable value. `isNull()` needs `nullable()`, because `null` is a missing value otherwise.

## Limitations

All of the following are false positives: NullAway reports correct code. None of them lets a `null` pass unnoticed, and each has a way to write the code without `@SuppressWarnings`. The messages were produced by NullAway 0.14.2 and 0.14.3 with JSpecify mode and `OnlyNullMarked`. The Kotlin compiler with `-Xjspecify-annotations=strict` has none of these limitations.

* **A lambda that implements a validator of a nullable value.** NullAway compares `Validated<@Nullable String>` with `Validated<X>` without replacing `X`. Write the validator as an anonymous class, or build it from an existing one: `Yavi._string(c -> c.trim()).nullable()`.
* **`Objects.requireNonNull` as the argument of a generic method.** NullAway infers the type argument from the nullable parameter. Assign the checked value to a variable first, or handle `null` in the expression. A lambda that validates a value that is not `null` is not affected.
* **`map` with a function that returns `null`, without a target type.** In the middle of a chain the mapped type is taken as not nullable. Give the type argument (`.<@Nullable String>map(...)`) or assign the validator to a declared type.
* **The parameter of a lambda that is a validator of a nullable value, inferred from a collection.** NullAway drops the nullable type argument. Use `var` for the result, declare the parameter type, or use a loop.

If NullAway reports correct code outside these cases, the validator type is the first thing to check: `nullable()` changes the type argument, and it is the only modifier that produces `null`.


---

# FILE: references/integrations-spring.md

# Spring

A Spring application uses YAVI at the boundary of a request: the schema reads the parameters or the body, and the result becomes a `BindingResult`, a response body or a redirect. YAVI does not depend on Spring; the adapters are functional interfaces that match Spring's method signatures.

## BindingResult

`ConstraintViolations#apply` accepts a function with the arguments of `BindingResult#rejectValue` and passes the violation messages:

```java
@PostMapping("/signup")
String signup(@RequestParam MultiValueMap<String, String> params, BindingResult result) {
    return switch (signupValidator.validate(params)) {
        case Validated.Valid<Signup>(Signup signup) -> {
            register(signup);
            yield "redirect:/";
        }
        case Validated.Invalid<Signup>(ConstraintViolations violations) -> {
            violations.apply(result::rejectValue);
            yield "signup";
        }
    };
}
```

The code of a field error is the message key (`object.type`), so a `MessageSource` replaces the message as before. `{0}` of that message is the label of the property if it has one. A text written in code is shown as it is; `violation.localizable()` tells the two cases apart.

Spring looks the message key up again in `rejectValue`, so a message of the bundle still wins there.

## MessageSource

`MessageSourceMessageFormatter` takes the functional interface of `MessageSource#getMessage` and delegates the formatting to Spring:

```java
@Bean
MessageFormatter messageFormatter(MessageSource messageSource) {
    return new MessageSourceMessageFormatter(messageSource::getMessage);
}
```

Give it to a validator with `formattingWith`; it applies to every violation of the validator, those of nested validators and of the reader included:

```java
ValueValidator<Map<String, ?>, Signup> signupValidator = Yavi.schema()
        ._string("email", c -> c.notBlank().email())
        .fromMap(Signup::new)
        .readingParameters()
        .formattingWith(messageFormatter);
```

## Showing a form again

Spring MVC creates a `BindingResult` only for a form object that it binds, not for a map of parameters. A `@ModelAttribute` method of the controller puts a `MapBindingResult` of the parameters into the model. A handler then takes the `BindingResult` as an argument, and `th:object`, `th:field` and `#fields` of Thymeleaf work as they do with a form object.

```java
@ModelAttribute
void signupForm(@RequestParam MultiValueMap<String, String> params, Model model) {
    Map<String, Object> form = ParameterTree.of(params).toParameters(signupValidator.description());
    model.addAllAttributes(new MapBindingResult(form, "signupForm").getModel());
}
```

* The `@ModelAttribute` method runs before every handler of the controller, so the GET handler renders the empty form. Without it a request fails with `An Errors/BindingResult argument is expected to be declared immediately after the model attribute`.
* One controller per form. Because the method runs before every handler, a controller with two forms would put both into the model, and a `BindingResult` argument resolves to the last model attribute added: every handler would receive the `BindingResult` of whichever form was added last, without an error. `@ModelAttribute("signupForm") BindingResult` does not select one either, since the model attribute is the form map rather than the `BindingResult`. Split the controller. To serve several forms from one controller, do the same work inside the handler instead: build the `MapBindingResult` from the parameters, add `getModel()` to the `Model`, and take no `BindingResult` argument.
* A field shows the text that was sent again, even if it is not of the type of its property (`abc` for `age`).
* Name a field as `th:field` does: `address.city`, `items[0].name`. These are the names of the violations and the keys that `MapBindingResult` looks up.
* `toParameters` gives the text of a single value and the list of a list property, so a text field shows `30` and every checked checkbox is checked again.
* Thymeleaf adds a hidden field `_subscribed` to a checkbox. No property is defined for that key, so such a form cannot be read with `rejectingUnknownProperties()`.
* The handler validates a `MultiValueMap`; a `Map<String, String>` would drop all but the first value.

## Validators in an IoC container

A validator built with `Yavi.schema()` is immutable and thread-safe, so it is registered as a bean like any other service:

```java
@Bean
ObjectInputValidator<User> userValidator() {
    return Yavi.schema()
            ._string("email", c -> c.notBlank().email())
            ._integer("age", c -> c.greaterThanOrEqual(0))
            .fromMap(User::new);
}
```

`ValidatorFactory` builds classic `Validator`s of `ValidatorBuilder` with a message key separator and a formatter, and `BiConsumerFactory` builds `BiConsumer<T, Errors>` for code that accepts Spring's `Validator#validate(Object, Errors)` signature:

```java
@Bean
BiConsumerFactory<Errors> biConsumerFactory(MessageSource messageSource) {
    MessageFormatter formatter = new MessageSourceMessageFormatter(messageSource::getMessage);
    return new BiConsumerFactory<>(".", formatter, Errors::rejectValue);
}
```

## WebFlux

A reactive handler validates the body and folds the result into a `ServerResponse`:

```java
RouterFunction<ServerResponse> routes() {
    return RouterFunctions.route()
        .POST("/users", request -> request.bodyToMono(UserRequest.class)
            .flatMap(body -> userValidator.validate(body)
                .map(UserRequest::toUser)
                .map(userService::create)
                .fold(violations -> ServerResponse.badRequest()
                        .body(ConstraintViolations.of(violations).details()),
                    created -> ServerResponse.ok().body(created))))
        .build();
}
```

`fold(errorsMapper, mapper)` is called when the body has been read. An invalid body produces `violations.details()`, which a JSON library serializes; see [Jackson](integrations-jackson.md#serializing-violations).


---

# FILE: references/integrations.md

# Integration Overview

YAVI has no runtime dependency other than JSpecify, and the interfaces that a framework needs are part of the library. A validator is a function: a schema reads an input, and the result is a `Validated` or its `ConstraintViolations`. Each integration below is a small adapter around that result.

| Integration | What it provides |
| --- | --- |
| [Spring](integrations-spring.md) | `BindingResult`, `MessageSource`, showing a form again, validators in an IoC container, WebFlux |
| [Jackson](integrations-jackson.md) | A `JsonNodeReader`, mapper settings for duplicate keys and number fidelity, serializing violations |
| [Kotlin](integrations-kotlin.md) | The `validator<T>` DSL, nullability with JSpecify, coroutine extensions |
| [NullAway](integrations-nullaway.md) | JSpecify annotations, common reports and fixes, limitations |

The input side is described in [JSON Trees](input-json.md) and [Request Parameters and Forms](input-parameters.md); the output side in [Writing an Object Back](writing-back.md).


---

# FILE: references/introduction.md

# Introduction

YAVI gives Java a Zod-like way to describe and validate input. A schema written in code reads untyped input, such as a parsed JSON document or a submitted form, and produces a typed object or a complete list of violations. This page explains that model, the older object-validation model it complements, and what the library guarantees.

## Two validation approaches

There are two ways to validate data:

1. Validate the input and create the object. The input is checked before the constructor runs, and the constructor is called only with valid values. An object that violates a rule cannot be created. This is the model of Zod and Raoh, and the main model of YAVI 0.18.
2. Validate an object that already exists. The object is created first and its fields are checked afterwards. This is the model of [Bean Validation](https://beanvalidation.org/): `new Car(null, "D", 1)` succeeds, and a separate call reports the violations.

`Yavi.schema()` with `fromMap(f)` implements the first model: it reads an untyped input by property name, checks each value, and passes the validated values to a function. `ValidatorBuilder` implements the second for an object that is created by something else, such as a framework or a deserializer.

## Why schema-first

The schema-first model has properties that object validation cannot offer:

* An invalid object never exists. There is no window in which a `Car` holds a negative `seatCount`.
* The schema describes the input, not the class. The same description reads a map, a JSON tree and request parameters, and can write the object back.
* A missing property is a violation by default. With object validation, a forgotten `notNull()` leaves `null` usable.
* The type of a validated value says whether it can be `null`. `nullable()` changes the type to `@Nullable`, and a nullness checker such as NullAway or the Kotlin compiler rejects a function that passes it to a non-null parameter.
* The input is read without reflection and without casts, so the rules can be checked statically where the schema is written.

The 0.18 API is therefore the recommended starting point. `Yavi.schema()` with `apply(f)` builds a validator of typed arguments, which is the direct successor of `Yavi.arguments()`, and with `fromMap(f)` it builds a validator of untyped input, which is the new capability of the release.

## Relation to Bean Validation

YAVI covers the constraints of Bean Validation with method calls rather than annotations. For example, `@NotNull`, `@Size`, `@Min`, `@Max`, `@Email`, `@Pattern` and `@Digits` have direct counterparts in the constraint API. Groups and conditional validation are available on `ValidatorBuilder`.

The differences are deliberate:

* There is no metadata layer. A constraint is a Java expression, so refactoring tools and the compiler see it.
* There is no `ConstraintValidator` registration and no `Validation.buildDefaultValidatorFactory()`.
* A schema can read raw input, not only an annotated object.
* Violations carry a name, a structured path, a JSON Pointer and a message key, so an API can return them directly.

The full mapping of annotations to YAVI constraints is in [Comparison with Bean Validation](coming-from-bean-validation.md).

## What YAVI guarantees

* `validate(input)` returns a `Validated<T>`: either `Validated.Valid` with the created object, or `Validated.Invalid` with every violation that was found.
* A function given to `fromMap`, `apply`, `flatFromMap` or `flatApply` is called only when all of its arguments are valid.
* A property is required unless a modifier says otherwise, and that modifier is visible in the type of the validated value.
* Violations are reported in a stable structure, with `name()`, `path()`, `pointer()` and `messageKey()`.
* A validator is immutable and thread-safe once built.
* No reflection is used to read properties, and no annotation processing is required.

YAVI does not decide what is valid. It evaluates the constraints that were written and reports the result.


---

# FILE: references/messages.md

# Messages and Localization

A violation has a message key and a message. The key identifies the rule, and the message is formatted with a `MessageFormatter` for the locale of the validation. A validator is given a formatter with `formattingWith`, and violations can be given another one when they are shown.

## MessageFormatter

```java
public interface MessageFormatter {
    String format(String messageKey, String defaultMessageFormat, Object[] args, Locale locale);

    default String format(String messageFormat, Object[] args, Locale locale) { ... }
}
```

The default implementation of the second method formats a text with `MessageFormat`. Override it to format a message written in code as the formatter formats the other messages. A key that the formatter does not know is formatted with the default message format, so a formatter replaces only the messages it has.

A formatter is called during validation and when a message is formatted. It must be thread-safe if a validator is shared.

## Resource bundles

Without Spring, `ResourceBundleMessageFormatter` looks a message up by its key in a resource bundle on the class path:

```java
// messages_ja.properties: numeric.lessThanOrEqual="{0}" は {1} 以下で入力してください
MessageFormatter formatter = new ResourceBundleMessageFormatter("messages");
validator.formattingWith(formatter).validate(input, Locale.JAPANESE);
```

The bundle is that of the locale of the validation (`messages_ja_JP`, then `messages_ja`), then the base bundle (`messages`). The bundle of the platform default locale is not a fallback, unlike `ResourceBundle.getBundle`: a validation in English on a Japanese server is not answered in Japanese. A key that the bundle does not have is formatted with the default message.

For Spring's `MessageSource`, use `MessageSourceMessageFormatter`; see [Spring](integrations-spring.md#messagesource).

## ViolationMessage and keys

A message of your own is a `ViolationMessage`: a message key, a format and the names of its arguments from `{1}` on:

```java
ViolationMessage outOfStock =
        ViolationMessage.of("order.outOfStock", "\"{0}\" exceeds the stock of {1}", "stock");
```

The message format keeps referring to the arguments by position: `{0}` is the name of the value and `{1}` the first argument. A violation built from it has `messageKey() = order.outOfStock` and `params() = {stock=3}`. A resource bundle can localize the key.

`ViolationMessage#withText(text)` keeps the key and the argument names and replaces the format with a text that no formatter replaces. `localizable()` tells a text from a message to look up.

## Messages written in code

A text given in code is the message of the violation. `MessageFormatter` no longer replaces it with a message it has for the message key; it only substitutes the arguments, and the key is kept.

* `message(String)` of a constraint is the message of the violation.
* `required(String)` and `typeMessage(String)` of a property are the messages of `object.required` and `object.type`.
* `message(...)` right after a constraint made of several predicates, such as `url(url -> ...)` or `password(...)`, replaces the message of each of them.

To localize the text, give it a key of its own with `ViolationMessage`:

```java
c -> c.notBlank().message(ViolationMessage.of("user.name.notBlank", "Enter your name"))
// messages_ja.properties: user.name.notBlank=名前を入力してください
```

`message(ViolationMessage)`, `required(ViolationMessage)` and `typeMessage(ViolationMessage)` are looked up by their own key as before.

## Overriding a message

`violations.apply(bindingResult::rejectValue)` of Spring MVC is not affected by the rule above: Spring looks the message key up again, so a message of the bundle still wins there. `violation.localizable()` tells the two cases apart.

A message is overridden where the rule or the property is defined, or when the violations are shown:

```java
ViolationMessage label = ViolationMessage.of("token.roles", "Select at least one role");
Yavi.schema()._list("roles", Yavi._string()).label("Roles").required(label)
        .fromMap(Token::new)
        .readingParameters()
        .formattingWith(new MessageSourceMessageFormatter(messageSource::getMessage));
```

`formattingWith` applies to every violation of the validator, those of nested validators and of the reader included. `ConstraintViolations#labeled(...).formattedWith(...)` does it when the violations are shown; `labeled` leaves a violation as it is when the function returns `null`.

## Locale

`validate(input, locale)` validates with the given locale, and `localizedWith(locale)` changes the locale of a result, a violation or a list of violations. A function given to `flatFromMap` or `flatApply` is not given the locale; its violations are reported with the locale of the validation.

The locale selects the resource bundle and formats the message with `MessageFormat`. A bundle that does not exist replaces no message, so a single base bundle localizes nothing by itself; give one bundle per locale.


---

# FILE: references/migration-0.17-to-0.18.md

# Migration from 0.17

YAVI 0.18.0 contains the following breaking changes from 0.17. They are listed with the changes that affect the most users first.

In the examples, "before" is code written for 0.17, "after" is the same code changed so that it compiles and behaves the same with 0.18, and "after (new API)" uses an API that is new in 0.18. See [Defining a Schema](defining-a-schema.md) for the new APIs.

"after" writes `Yavi.schema()` where "before" writes `Yavi.arguments()`. `Yavi.arguments()` still compiles with 0.18 but is deprecated; see [`Yavi.arguments()` is deprecated and `YaviArguments` is `YaviSchema`](#yaviarguments-is-deprecated-and-yaviarguments-is-yavischema).

## Java 21 is required

YAVI 0.18.0 is compiled for Java 21. 0.17 ran on Java 8.

### Who is affected

* An application that runs on Java 8 to 20. It stays on 0.17.
* Code compiled against 0.17, such as a library that uses YAVI. `Validation` is an interface now and the methods of `Yavi.arguments()` return other types, so it fails with 0.18 at run time until it is recompiled.

### Migration

#### 1. Run on Java 21 or later

#### 2. Recompile the code that uses YAVI

This is needed also where the source does not change.

### Related pull requests

* [#532](https://github.com/making/yavi/pull/532) raises the baseline to Java 21.

## A validated value is required by default

An argument of `Yavi.schema()` and a validator of a single value (`StringValidatorBuilder` and so on) now reject `null` without `notNull()`. A value that may be `null` has to say so with `nullable()`, which is new in 0.18.0. See [Optional and Default Values](optional-and-defaults.md#accepting-null).

```java
record Member(String name, @Nullable String nickname) {}

Arguments2Validator<String, @Nullable String, Member> validator = Yavi.schema()
        ._string("name", c -> c.lessThanOrEqual(50))                // null was valid, is a violation now
        ._string("nickname", c -> c.lessThanOrEqual(20)).nullable() // null is valid
        .apply(Member::new);
```

`nullable()` also changes the type of the validated value to `@Nullable`, which matters for code checked by NullAway and for Kotlin.

### Who is affected

Affected:

* An argument of `Yavi.arguments()`.
* A validator of a single value built with `StringValidatorBuilder`, `IntegerValidatorBuilder` and so on, with `of(name, constraints)` or with `wrap(b -> ...)`.
* `ValueValidator.passThrough()`, in its type only.
* `Validation` used directly: `value()` and `valueNullable()`.

Not affected:

* `ValidatorBuilder` and `Validator`. A property that is `null` is still valid unless a constraint such as `notNull()` rejects it:

```java
Validator<Car> validator = ValidatorBuilder.<Car>of()
        .constraint(Car::manufacturer, "manufacturer", c -> c.notNull())
        .constraint(Car::seatCount, "seatCount", c -> c.greaterThanOrEqual(2)) // null is still valid
        .build();
```

* `ArgumentsValidatorBuilder.of(f).builder(b -> ...)` and the meta classes that the annotation processor generates for it.
* `validator.applicative()`.

### Migration

Steps 1 and 2 apply to every user. Step 3 applies to code checked by NullAway and to Kotlin. Step 4 is optional.

#### 1. Add `nullable()` to a value that may be `null`

Such a value has no constraint that rejects `null` (`notNull()`, `notBlank()`, `notEmpty()` and so on). Without `nullable()`, `null` is now a violation with `object.notNull`.

An argument:

```java
// before
Yavi.arguments()
        ._string("name", c -> c.notBlank())
        ._string("nickname", c -> c.lessThanOrEqual(20))
        .apply(Member::new);

// after
Yavi.schema()
        ._string("name", c -> c.notBlank())
        ._string("nickname", c -> c.lessThanOrEqual(20)).nullable()
        .apply(Member::new);

// after (new API)
// optional() and defaultValue(...) accept null too and keep it out of the validated value
Yavi.schema()
        ._string("name", c -> c.notBlank())
        ._string("nickname", c -> c.lessThanOrEqual(20)).optional() // Optional<String>
        .apply(Member::new);

Yavi.schema()
        ._string("name", c -> c.notBlank())
        ._string("nickname", c -> c.lessThanOrEqual(20)).defaultValue("") // String
        .apply(Member::new);
```

A single value:

```java
// before
ValueValidator<String, String> memo = StringValidatorBuilder
        .of("memo", c -> c.lessThanOrEqual(100)).build();

// after
ValueValidator<String, @Nullable String> memo = StringValidatorBuilder
        .of("memo", c -> c.lessThanOrEqual(100)).build().nullable();

// after (new API)
ValueValidator<String, @Nullable String> memo = Yavi._string("memo", c -> c.lessThanOrEqual(100)).nullable();
```

#### 2. Add `nullable()` to a value constrained with `isNull()`

Without it no value is valid.

```java
// before
Yavi.arguments()._string("id", c -> c.isNull())

// after
Yavi.schema()._string("id", c -> c.isNull()).nullable()
```

#### 3. With NullAway or Kotlin, declare the receiver of a nullable value as nullable

Java code that is not checked by a nullness checker compiles without this step.

* The parameter of the constructor or function given to `apply` that receives a `nullable()` argument: `@Nullable String`, in Kotlin `String?`. The other parameters no longer have to accept `null`.
* The type argument of a declared validator: `ValueValidator<String, @Nullable String>`, `Validated<@Nullable String>`.
* `ValueValidator.passThrough()`: `ValueValidator<X, @Nullable X>`.

```kotlin
data class Member(val name: String, val nickname: String?)

Yavi.schema()
    ._string("name") { it.notBlank() }
    ._string("nickname") { it.lessThanOrEqual(20) }.nullable()
    .apply(::Member)
```

NullAway reports a parameter that is not declared `@Nullable` like this:

```
[NullAway] parameter age of referenced method is @NonNull, but parameter in functional interface method am.ik.yavi.fn.Function2.apply(String,@Nullable Integer) is @Nullable
```

See [Limitations](integrations-nullaway.md#limitations) if NullAway reports correct code.

#### 4. Optional cleanup

Nothing below is required. The code before works and behaves as it did.

* A `notNull()` that only made the value required can be removed. Keep it to give the violation of `null` another message.

```java
// before
Yavi.arguments()
        ._string("name", c -> c.notNull())
        ._integer("age", c -> c.notNull().greaterThanOrEqual(0))
        .apply(Member::new);

// after
Yavi.schema()
        ._string("name")
        ._integer("age", c -> c.greaterThanOrEqual(0))
        .apply(Member::new);
```

* `valueNullable()` is deprecated. `value()` returns the same value, also for a success that holds `null`.

```java
// before
@Nullable String value = validated.valueNullable();

// after
@Nullable String value = validated.value();
```

### All changes

Behavior:

| | Before | After |
| --- | --- | --- |
| `null` for an argument or a single value whose constraints do not reject `null` | valid, the value is `null` | a violation with `object.notNull` |
| `null` for a value with a constraint that rejects it (`notBlank()`, `notNull()`) | the violation of that constraint | unchanged |
| `isNull()` on an argument or a single value | accepts only `null` | no value is valid without `nullable()` |
| `Validation.Success#value()` for a success that holds `null` | throws `NoSuchElementException` | returns `null`; `valueNullable()` is deprecated |

Types:

| | Before | After |
| --- | --- | --- |
| Parameters of the function given to `apply` | `@Nullable` for every argument | `@Nullable` only for a `nullable()` argument |
| `ValueValidator.passThrough()` | `ValueValidator<X, X>` | `ValueValidator<X, @Nullable X>` |

The changes of types are annotations, so they are binary compatible, and source compatible for Java code that is not checked by a nullness checker.

### Why

Whether a value accepted `null` was decided inside its constraint lambda (`c -> c.notNull()`). The type of the value was the same with and without it, so neither the compiler nor a nullness checker could see a forgotten `notNull()`:

```java
record Member(String name, int age) {}

Arguments2Validator<String, Integer, Member> validator = Yavi.arguments()
        ._string("name", c -> c.notBlank())
        ._integer("age", c -> c.greaterThanOrEqual(0)) // notNull() is missing
        .apply(Member::new);

validator.validate("Taro", null); // before: NullPointerException, thrown out of validate
```

[NullAway](https://github.com/uber/NullAway) checks nullness through types only, so it could not tell the two cases apart either. The parameters of the function given to `apply` were `@Nullable` for every argument, and `apply(Member::new)` was reported even for values validated with `notNull()`.

Now a value is required unless it says otherwise, and saying otherwise changes its type, as in Zod and Raoh. A value is `null` only where its type says so, which NullAway and Kotlin can check.

### Related pull requests

* [#557](https://github.com/making/yavi/pull/557) makes a validated value required and lets `nullable()` change its type.
* [#556](https://github.com/making/yavi/pull/556) is its precondition: the function given to `apply` receives the validated values without `@Nullable` parameters.

## `ViolationDetail` is a record

`ConstraintViolations#details()` returns records that say which value failed. Their accessors have other names, and so have the properties of the JSON that a JSON library writes from them. The positional `args` are replaced by `params`, the arguments by name without the name of the value and without the value that violated the constraint. See [Violations](violations.md#violationdetail).

```java
List<ViolationDetail> details = violations.details();
// [{"name": "items[1].quantity", "pointer": "/items/1/quantity", "messageKey": "numeric.lessThanOrEqual",
//   "message": "\"items[1].quantity\" must be less than or equal to 99", "params": {"max": 99}}]
```

### Who is affected

Affected:

* Code that calls `getKey()`, `getArgs()` or `getDefaultMessage()` of a `ViolationDetail`, or its constructor.
* A client of an API that returns `details()` as JSON, in particular one that reads `args`.
* A custom constraint or a hand-written violation whose arguments a client reads: they are in `params` only if the message names them.
* Code that modifies the list returned by `details()`.

Not affected:

* `ConstraintViolation`: `name()`, `messageKey()`, `args()` and `message()`.

### Migration

#### 1. Rename the accessors and read the arguments from the violation

```java
// before
for (ViolationDetail detail : violations.details()) {
    String key = detail.getKey();
    Object[] args = detail.getArgs();
    String message = detail.getDefaultMessage();
}

// after: a detail has no positional arguments, a violation has
for (ConstraintViolation violation : violations) {
    String key = violation.messageKey();
    Object[] args = violation.args();
    String message = violation.message();
}

// after (new API)
for (ViolationDetail detail : violations.details()) {
    String name = detail.name();                // items[1].quantity
    String pointer = detail.pointer();          // /items/1/quantity, a JSON Pointer
    Map<String, Object> params = detail.params(); // {max=99}
}
```

#### 2. Follow the new JSON in the client, or keep the JSON of 0.17

```json
// before
[{"key": "charSequence.notBlank", "args": ["items[1].name", ""], "defaultMessage": "\"items[1].name\" must not be blank"}]

// after
[{"name": "items[1].name", "pointer": "/items/1/name", "messageKey": "charSequence.notBlank",
  "message": "\"items[1].name\" must not be blank", "params": {}}]
```

To keep the JSON of 0.17, which sends the violated value back, map the violations to a type of your own:

```java
record LegacyDetail(String key, List<Object> args, String defaultMessage) {}

List<LegacyDetail> details = violations.stream()
        .map(violation -> new LegacyDetail(violation.messageKey(), Arrays.asList(violation.args()), violation.message()))
        .toList();
```

#### 3. Name the arguments of your own messages

The arguments of a built-in constraint have names. Those of a message of your own are in `params` only if the message names them:

```java
// before: "args": ["quantity", 3, 5]
ViolationMessage.of("order.outOfStock", "\"{0}\" exceeds the stock of {1}");

// after (new API): "params": {"stock": 3}
ViolationMessage.of("order.outOfStock", "\"{0}\" exceeds the stock of {1}", "stock");
```

### All changes

| | Before | After |
| --- | --- | --- |
| Message key | `getKey()`, JSON `key` | `messageKey()`, JSON `messageKey` |
| Formatted message | `getDefaultMessage()`, JSON `defaultMessage` | `message()`, JSON `message` |
| Arguments | `Object[] getArgs()`, JSON `args`: positional, starting with the name and ending with the violated value | `Map<String, Object> params()`, JSON `params`: by name, without the name and the violated value, unmodifiable. The positional arguments are `ConstraintViolation#args()` |
| Name and JSON Pointer of the value | not available | `name()`, `pointer()` |
| Type | a class | a sealed interface of the records `ViolationDetail.Simple` and `ViolationDetail.NoAlternativeMatched` |
| Details of the alternatives of `ValueValidator.anyOf` | not available | `alternatives()` of `ViolationDetail.NoAlternativeMatched`, JSON `alternatives` |
| Constructor | `ViolationDetail(key, args, defaultMessage)` | `ViolationDetail.Simple(name, pointer, messageKey, message, params)` |
| List returned by `details()` | modifiable | unmodifiable |

### Why

A detail did not say which value failed: the name was only the first element of `args`. `defaultMessage` was the formatted message, not the default one.

A client that rendered its own message had to know, for each message key, which position of `args` holds what, and that table was not part of the API. `args` also ended with the violated value, so returning `details()` sent a rejected password or token back unless every caller mapped the details to a type of its own.

### Related pull requests

* [#551](https://github.com/making/yavi/pull/551) makes `ViolationDetail` a record and adds `messagesByName()`, `messagesByPointer()` and `pointer()`.
* [#566](https://github.com/making/yavi/pull/566) makes it a sealed interface of two records, of which `ViolationDetail.NoAlternativeMatched` has `alternatives`.
* [#568](https://github.com/making/yavi/pull/568) replaces `args` with `params`.

## The violations of a lifted collection are located under the index

`liftList()`, `liftSet()` and `liftCollection()` put the index of an element before the name of the element validator, where they put it after the name. Element validation is described in [Objects and Collections](objects-and-collections.md#lists).

```java
Yavi._string("tag", c -> c.notBlank())
        .liftList()
        .validate(List.of("java", "")); // [1].tag, was tag[1]
```

The code compiles as it is. The names of the violations change.

### Who is affected

Affected:

* Code that looks up a violation of a lifted validator by its name, such as the field of a form or an assertion of a test, where the element validator has a name.
* Code that calls `indexed(int)`.

Not affected:

* `ValidatorBuilder#forEach`.
* A lifted validator whose element has the empty name. It reports `[1]` as before.

### Migration

#### 1. Name the collection, not the element

```java
// before
StringValidatorBuilder.of("tag", c -> c.notBlank()).build()
        .liftList()
        .validate(List.of("java", "")); // tag[1]

// after
StringValidatorBuilder.of("", c -> c.notBlank()).build()
        .liftList().prefixed("tag")
        .validate(List.of("java", "")); // tag[1]

// after (new API)
Yavi._string(c -> c.notBlank())
        .liftList().prefixed("tag")
        .validate(List.of("java", "")); // tag[1]
```

An element that is an object keeps the names of its properties. With `prefixed`, it is named like an element of `ValidatorBuilder#forEach`:

```java
// before
addressValidator.applicative().liftList().validate(addresses); // street[1]

// after
addressValidator.applicative().liftList().prefixed("addresses").validate(addresses); // addresses[1].street
```

#### 2. Replace `indexed(int)` with `prefixed(int)`

`indexed(int)` is removed from `ConstraintViolation`, `Validated`, `ValueValidator` and `Arguments1Validator`. `prefixed(int)` of `ConstraintViolation` and `Validated` puts the index before the name.

```java
// before
validated.indexed(1); // tag[1]

// after
validated.prefixed(1); // [1].tag
```

### Why

The name did not follow the structure of the input: the property `street` of the second address was `street[1]`, which reads as the second element of `street`.

### Related pull requests

* [#544](https://github.com/making/yavi/pull/544) locates the violations of lifted elements under the index and removes `indexed(int)`.

## A message written in code is not replaced by the formatter

A text given in code with `message(String)` of a constraint, or with `required(String)` and `typeMessage(String)` of a property, is the message of the violation. A `MessageFormatter` such as `MessageSourceMessageFormatter` no longer replaces it with a message it has for the message key of the constraint; it only substitutes the arguments. The message key is kept. See [Messages and Localization](messages.md#messages-written-in-code).

```java
// messages.properties: charSequence.notBlank={0} must not be blank.
Validator<User> validator = ValidatorBuilder.<User>of()
        .messageFormatter(new MessageSourceMessageFormatter(messageSource::getMessage))
        ._string(User::name, "name", c -> c.notBlank().message("Enter your name"))
        .build();

validator.validate(new User("")).get(0).message();
// before: name must not be blank.
// after:  Enter your name
```

`message(...)` right after a constraint made of several predicates, `url(url -> ...)` and `password(policies -> ...)`, replaces the message of each of them, not that of the last one only.

```java
._string(Site::url, "url", c -> c.url(url -> url.protocol("http", "https").build()).message("Enter an http URL"))
// "javascript:alert(1)" (charSequence.url)
// before: "url" must be a valid URL
// after:  Enter an http URL
```

### Who is affected

Affected:

* A `message(String)`, `required(String)` or `typeMessage(String)` whose message key the formatter of the validator has a message for, typically a `MessageSourceMessageFormatter` with a resource bundle that localizes the default messages. The text is now shown in every locale.
* `message(...)` right after `url(url -> ...)` with `protocol`, `host` or `port`, or after `password(...)` with more than one policy.
* A `MessageFormatter` of your own that does more than look up a message: a text is given to the new `format(String messageFormat, Object[] args, Locale locale)`, which formats it with `MessageFormat` unless it is overridden.
* `ConstraintViolation.builder().name(...).message(String)`, whose message key `_` is not looked up any more.

Not affected:

* `message(ViolationMessage)`, `required(ViolationMessage)` and `typeMessage(ViolationMessage)`, which are looked up by their own key as before.
* The message key and the arguments of a violation, and so a `ViolationDetail`.
* A validator with the default `SimpleMessageFormatter`, which looks up nothing.
* `violations.apply(bindingResult::rejectValue)` of Spring MVC: Spring looks the message key up again, so a message of the bundle still wins there. `violation.localizable()` tells a text from a message to look up.

### Migration

#### 1. Remove a text that the formatter replaced

The text was not shown in 0.17. Without it, the violation reads as it did.

```java
// before
c -> c.notBlank().message("Enter your name")

// after: the message of the bundle, as in 0.17
c -> c.notBlank()
```

#### 2. Give a text to localize a key of its own

```java
// after
c -> c.notBlank().message(ViolationMessage.of("user.name.notBlank", "Enter your name"))
// messages_ja.properties: user.name.notBlank=名前を入力してください
```

#### 3. Give one predicate of `url(...)` or `password(...)` a message of its own

```java
// before: the text is that of the protocol only
c -> c.url(url -> url.protocol("http", "https").build()).message("Enter an http URL")

// after: the same messages as 0.17
c -> c.url(url -> {
    List<ConstraintPredicate<String>> predicates = new ArrayList<>(url.protocol("http", "https").build());
    predicates.set(1, predicates.get(1).overrideMessage("Enter an http URL"));
    return predicates;
})
```

### Why

A text written for one property is more specific than a message that a bundle has for every violation of the key. In 0.17 the more specific one silently lost as soon as the application localized the default messages. The key is kept so that a client that tells violations apart by the key still does.

`message(...)` replaced the message of the last predicate that a constraint added, which for `url(...)` depends on how it is built: the text was shown for `ftp://example.com` (`charSequence.url.protocol`) and not for `javascript:alert(1)` (`charSequence.url`).

### Related pull requests

* [#575](https://github.com/making/yavi/pull/575)

## The message of a value without a name

The message of a violation whose name is empty says "The value" where it had the quoted empty name.

```java
Yavi._string(c -> c.notBlank()).validate(""); // The value must not be blank
```

### Who is affected

Affected:

* An assertion on, or a display of, the default message of a validator with the empty name: `StringValidatorBuilder.of("", ...)` and so on.

Not affected:

* The message key and the arguments. The name is still `""`.
* A message that a `MessageSource` formats with a format of its own.
* A violation with a name (`"tags[0]" must not be blank`).

### Migration

#### 1. Update the expected messages

```java
// before
StringValidatorBuilder.of("", c -> c.notBlank()).build().validate("");
// "" must not be blank

// after
StringValidatorBuilder.of("", c -> c.notBlank()).build().validate("");
// The value must not be blank

// after (new API)
Yavi._string(c -> c.notBlank()).validate("");
// The value must not be blank
```

### Related pull requests

* [#546](https://github.com/making/yavi/pull/546) adds the validators of a single value to `Yavi` and changes the message.

## The nullness annotations are those of JSpecify

The package `am.ik.yavi.jsr305` is removed. YAVI is annotated with [JSpecify](https://jspecify.dev) (`@NullMarked`, `@Nullable`) instead. See [NullAway](integrations-nullaway.md#jspecify-annotations).

### Who is affected

Affected:

* Code that imports an annotation of `am.ik.yavi.jsr305`.
* Code checked by NullAway, and Kotlin (2.1 or later reports a mismatch with JSpecify annotations as an error). They now check the nullness of every parameter and result of YAVI.

Not affected:

* Any other Java code.

### Migration

#### 1. Import the annotations of JSpecify

YAVI does not bring `org.jspecify:jspecify`. Add it to your dependencies.

```java
// before
import am.ik.yavi.jsr305.Nullable;

// after
import org.jspecify.annotations.Nullable;
```

#### 2. With NullAway or Kotlin, fix the reported nullness

* A value that may be `null` is declared so, as described in [step 3 of the required default](#3-with-nullaway-or-kotlin-declare-the-receiver-of-a-nullable-value-as-nullable).
* The validated type of the Kotlin DSL is not nullable: `validator<T> { ... }`, `nest` and `forEach` declare `T : Any`.

See [Limitations](integrations-nullaway.md#limitations) if NullAway reports correct code.

### Related pull requests

* [#534](https://github.com/making/yavi/pull/534) replaces JSR 305 with JSpecify.
* [#556](https://github.com/making/yavi/pull/556) reduces `@Nullable` to the places where `null` is part of the contract.

## Other changes

These affect few users.

### `Validation` is an interface

`Validation` is an interface and `Validated` a sealed interface. A class that extends `Validation` implements it instead, and `map` / `flatMap` have one type parameter. Code that calls them without type arguments on a `Validated` compiles as it is.

```java
// before
class Result<T> extends Validation<String, T> { ... }
Validated<Integer> number = validated.<Integer, Validated<Integer>>map(Integer::valueOf);

// after
class Result<T> implements Validation<String, T> { ... }
Validated<Integer> number = validated.<Integer>map(Integer::valueOf);
```

Related pull requests: [#537](https://github.com/making/yavi/pull/537), [#549](https://github.com/making/yavi/pull/549)

### A combination of validation results returns a declared type

`apply` of a combination returned a type that the caller chose, and the compiler did not check the choice. It now returns the type it is declared with:

* `Validated#combine` returns the new `ValidatedCombiningN`, whose `apply` returns `Validated<R>`.
* `Validation#apply`, `CombiningN#apply` and `Validations.apply` return `Validation<E, R>`.
* `Validation#yieldSuccess` and `yieldFailure` are removed.

Code that combines `Validated` results with `combine` and assigns the result to a `Validated` compiles as it is. The result is a `Validated` also with `var` and in a `switch` now.

```java
// before
Validated<Address> address = Validations.apply(Address::new, country, street);
Validated<Address> address = Validations.combine(country, street).apply(Address::new);
Validated<Address> address = country.combine(street).<Address, Validated<Address>>apply(Address::new);

// after
Validated<Address> address = country.combine(street).apply(Address::new);
```

A combination that starts with a `Validation<ConstraintViolation, T>` returns a `Validation`, which is not assignable to a `Validated`. Convert the first one with `Validated.of`. Before, the last validation of the combination decided the type at run time, and the assignment failed with a `ClassCastException` if that one was not a `Validated`.

```java
Validation<ConstraintViolation, Country> country = ...;

// before
Validated<Address> address = country.combine(street).apply(Address::new);

// after
Validated<Address> address = Validated.of(country).combine(street).apply(Address::new);
```

An implementation of `Validation` that overrode `yieldSuccess` and `yieldFailure` to return its own type overrides `map`, `apply` and `combine` instead, as `Validated` does.

Related pull request: [#558](https://github.com/making/yavi/pull/558)

### Deprecated and redundant members are removed

| Removed | Use instead |
| --- | --- |
| `ValueValidator#andThen(Function)`, `ArgumentsNValidator#andThen(Function)` | `map(Function)`. `andThen(ValueValidator)` is not affected. |
| `new ConstraintViolation(...)` | `ConstraintViolation.builder()` or `ConstraintViolation.of(...)` |
| `new SimpleMessageFormatter()` | `SimpleMessageFormatter.getInstance()` |
| `new Validations()`, `new Functions()` | Nothing. They have static methods only. |
| The field `Validation.Success#value` | `value()` |

```java
// before
new ConstraintViolation("name", "notBlank", "\"{0}\" must not be blank", new Object[] { "name", "" },
        new SimpleMessageFormatter(), Locale.ENGLISH);

// after
ConstraintViolation.builder()
        .name("name")
        .messageKey("notBlank")
        .defaultMessageFormat("\"{0}\" must not be blank")
        .args("name", "")
        .locale(Locale.ENGLISH)
        .build();
```

`Validation.Success` and `Validation.Failure` are records. `toString()` returns `Success[value=a]` and `Failure[errors=[e]]`.

Related pull request: [#558](https://github.com/making/yavi/pull/558)

### The constructors of `ArgumentsNValidatorBuilder` are removed

```java
// before
new Arguments2ValidatorBuilder<>(nameValidator, ageValidator).apply(Member::new);

// after
Yavi.schema()._string(nameValidator)._integer(ageValidator).apply(Member::new);
```

Related pull request: [#538](https://github.com/making/yavi/pull/538)

### An enum and an object of a schema are added with their type

A property added without its type could not be read from a map: `fromMap` threw an `IllegalStateException` when the validator was built. The methods without a type are removed, so a schema serves `apply` and `fromMap` alike.

| Removed | Use instead |
| --- | --- |
| `_enum(name)`, `_enum(name, constraints)` of the schema builders | `_enum(name, type)`, `_enum(name, type, constraints)` |
| `_object(name)`, `_object(name, constraints)` of the schema builders | `_object(name, type)`, `_object(name, type, constraints)`; for a type without a class literal, `_object(Yavi.<List<String>>_object(name, constraints))` |
| `EnumValidatorBuilder.of(name, constraints)`, `EnumValidatorBuilder.wrap(builder)` | `EnumValidatorBuilder.of(name, type, constraints)`, `EnumValidatorBuilder.wrap(type, builder)` |
| `new EnumValidator<>(validator, mapper)` | `new EnumValidator<>(validator, mapper, type)` |

```java
// before
Yavi.arguments()
        ._string("name")
        .<Role>_enum("role", c -> c.oneOf(Role.USER, Role.ADMIN))
        .<Address>_object("address")
        .apply(User::new);

// after
Yavi.schema()
        ._string("name")
        ._enum("role", Role.class, c -> c.oneOf(Role.USER, Role.ADMIN))
        ._object("address", Address.class)
        .apply(User::new);
```

The description of such an enum now holds its constants, so its JSON Schema has `enum`.

Related pull request: [#565](https://github.com/making/yavi/pull/565)

### Two arguments of `apply` cannot have the same name

`apply` and `flatApply` throw an `IllegalArgumentException` when two arguments have the same name, as `fromMap` does: the validator would describe an object in which one property stands for two arguments. Give each argument its own name.

```java
// before: built a validator whose JSON Schema had one property "value" for both arguments
Yavi.arguments()._integer("value")._integer("value").apply(Range::new);

// after
Yavi.schema()._integer("from")._integer("to").apply(Range::new);
```

Related pull request: [#565](https://github.com/making/yavi/pull/565)

### `Yavi.arguments()` is deprecated and `YaviArguments` is `YaviSchema`

`Yavi.schema()` is the new name of `Yavi.arguments()`, which still works and is deprecated. The builder now describes an input that is read from typed arguments, a map, a JSON tree or request parameters, so its type `YaviArguments` is renamed to `YaviSchema`. Code that declares a variable of that type must rename it. See [Defining a Schema](defining-a-schema.md).

```java
// before
YaviArguments builder = Yavi.arguments();

// after
YaviSchema builder = Yavi.schema();
```

### `Arguments1` to `Arguments16` are records

`toString()` returns `Arguments2[arg1=a, arg2=1]`. It was `Arguments2{arg1=a, arg2=1}`.

Related pull request: [#549](https://github.com/making/yavi/pull/549)

### `andThen` takes a validator of a subtype

`ValueValidator#andThen` and `ArgumentsNValidator#andThen` take a `ValueValidator<? super X, ? extends X2>`. They took a `ValueValidator<? super X, X2>`. A call compiles as before. A class that overrides `andThen` declares the new type of the parameter.

```java
// before
@Override
public <X2> ValueValidator<String, X2> andThen(ValueValidator<? super Name, X2> validator) { ... }

// after
@Override
public <X2> ValueValidator<String, X2> andThen(ValueValidator<? super Name, ? extends X2> validator) { ... }
```

Related pull request: [#572](https://github.com/making/yavi/pull/572)

### A lifted validator takes a container of a subtype

`liftList()`, `liftSet()`, `liftCollection(factory)` and `liftOptional()` of `ValueValidator` and `Arguments1Validator`, and the static methods of the same names of `ValueValidator` and `ArgumentsValidators`, return a validator of `Iterable<? extends T>` or `Optional<? extends T>`. They returned a validator of `Iterable<T>` or `Optional<T>`, which rejected a `List<String>` where `T` is `Object`. A call that validates at once compiles as before. A variable, a parameter or a return type that declares the lifted validator declares the new type, or `var`.

```java
// before
ValueValidator<Iterable<String>, List<String>> tags = tagValidator.liftList();
Arguments1Validator<Optional<String>, Optional<PhoneNumber>> phone = phoneNumberValidator.liftOptional();

// after
ValueValidator<Iterable<? extends String>, List<String>> tags = tagValidator.liftList();
Arguments1Validator<Optional<? extends String>, Optional<PhoneNumber>> phone = phoneNumberValidator.liftOptional();
```

Related pull request: [#576](https://github.com/making/yavi/pull/576)

### `build()` of a builder of a single value returns a validator that knows its reverse

`build()` of `StringValidatorBuilder`, `IntegerValidatorBuilder` and the other builders of single values returns `StringValidator.Reversible`, `IntegerValidator.Reversible` and the like. It returned `StringValidator<String>`, `IntegerValidator<Integer>` and the like, which the new types extend, so code that declares the old type compiles as it is. Code compiled with 0.17 is recompiled, as for the other changes.

A variable declared with `var` has the new type, which a mapped validator is not assigned to. Declare the type, or use another variable:

```java
// before
var name = StringValidatorBuilder.of("name", c -> c.notBlank()).build();
name = name.map(String::strip);

// after
StringValidator<String> name = StringValidatorBuilder.of("name", c -> c.notBlank()).build();
name = name.map(String::strip);
```

The new type tells that the validator can be written back; see [Writing an Object Back](writing-back.md).

Related pull request: [#579](https://github.com/making/yavi/pull/579)

### `emoji()` counts extended grapheme clusters

A few sequences that are not emoji count as one where they counted as two: `"\r\n"`, or a half-width katakana with a voiced sound mark (`ｶﾞ`). The class `Emoji` is removed. See [Built-in Constraints](built-in-constraints.md#character-counting-and-byte-size).

Related pull request: [#533](https://github.com/making/yavi/pull/533)

### The formats of a string accept an empty string

`ipv4()`, `ipv6()`, `luhn()`, `isoLocalDate()` and `localDate(pattern)` of `CharSequenceConstraint` accept `""`, as `email()`, `url()`, `uuid()` and `isInteger()` always did. In 0.17 an optional text was valid or not when left empty depending on its format. Add `notBlank()` or `notEmpty()` where `""` must be rejected. See [Built-in Constraints](built-in-constraints.md#string-and-charsequence).

```java
// before: "" is a violation (charSequence.ipv4)
ValidatorBuilder.<Server>of()._string(Server::address, "address", c -> c.ipv4()).build();

// after: the same result with 0.18
ValidatorBuilder.<Server>of()._string(Server::address, "address", c -> c.notEmpty().ipv4()).build();
```

Related pull request: [#573](https://github.com/making/yavi/pull/573)

### The message key separator applies under `forEach`

A `ValidatorBuilder` with a message key separator other than `.` uses it in the names under `forEach(..., builder -> ...)` too.

```java
new ValidatorBuilder<Order>("/")
        .forEach(Order::addresses, "addresses", b -> b.constraint(Address::street, "street", c -> c.notBlank()))
        .build();
// before: addresses[0].street
// after:  addresses[0]/street
```

Related pull request: [#537](https://github.com/making/yavi/pull/537)

### The constructors of the nested validators take the path

The constructors of `NestedValidator`, `NestedCollectionValidator` and `NestedConstraintPredicates` take the path as an additional argument.

Related pull request: [#537](https://github.com/making/yavi/pull/537)

### `toString()` of a violation is its pointer, its message and its key

`ConstraintViolation#toString()` returns `/age: "age" must be less than or equal to 150 (numeric.lessThanOrEqual)`, and `ConstraintViolations#toString()` the list of them. It was `ConstraintViolation{name='age', messageKey='numeric.lessThanOrEqual', defaultMessageFormat='"{0}" must be less than or equal to {1}', args=[age, 150, 300]}`. The violated value is no longer printed unless the message shows it. Code that compares the text, such as an assertion of a test, compares `messageKey()`, `name()` and `args()` instead.

Related pull request: [#584](https://github.com/making/yavi/pull/584)

### The char sequence constraints are in `am.ik.yavi.constraint`

`ByteSizeConstraint`, `CodePointsConstraint` and `EmojiConstraint` are in `am.ik.yavi.constraint` instead of `am.ik.yavi.constraint.charsequence`. The fluent methods of `CharSequenceConstraint` return them as before; code that imports them uses the other package.


---

# FILE: references/objects-and-collections.md

# Objects and Collections

A property can be a nested object, a list or a map. This page also covers properties that are read from the same map, unknown keys, schemas whose properties are known at run time, and recursive structures.

## Nested objects

A nested object is added with `_object(name, validator)`. The validator is built with `fromMap` or `from` and reads a nested map or node:

```java
ObjectInputValidator<Address> addressValidator = Yavi.schema()
        ._string("street", c -> c.notBlank())
        ._string("city", c -> c.notBlank())
        .fromMap(Address::new);

ObjectInputValidator<User> userValidator = Yavi.schema()
        ._string("email", c -> c.notBlank().email())
        ._object("address", addressValidator)
        .fromMap(User::new);
```

A violation of the nested value is located under the property name, in `name()` (`address.street`) and in `path()`. A nested validator can be reused in several schemas, and a validator defined for a map also serves a JSON tree when the outer validator is read with `readingWith(reader)`.

## Lists

`_list(name, elementValidator)` validates every element with the given validator. The violations of an element are located under its index:

```java
ObjectInputValidator<User> userValidator = Yavi.schema()
        ._string("email", c -> c.notBlank().email())
        ._list("roles", Yavi._string(c -> c.notBlank())) // roles[0]
        ._list("tags", Yavi._string(c -> c.notBlank()),
                c -> c.notEmpty().lessThanOrEqual(10).unique()) // tags
        .fromMap(User::new);
```

* The elements are required like any value. Give `elementValidator.nullable()` for a `List<@Nullable String>`.
* The constraints of `_list` are checked on the validated elements, only when every element is valid, and are reported on the property (`roles`).
* `unique(key)` makes the elements unique by a key of them, such as an identifier. The duplicated keys are in the message and in `params`.
* An element validator with an empty name reports a violation on the element itself rather than on a property of it.
* `_list` with a validator that reads an object reports `addresses[0].street`.

The program below reports a blank street and a blank element with the names that locate each violation, `address.street` and `roles[1]`.

```java runnable
import java.util.List;
import java.util.Map;

import am.ik.yavi.core.ConstraintViolation;
import am.ik.yavi.core.ConstraintViolations;
import am.ik.yavi.input.ObjectInputValidator;
import am.ik.yavi.validator.Yavi;

public class Main {

    record Address(String street, String city) {
    }

    record User(String email, Address address, List<String> roles) {
    }

    static final ObjectInputValidator<Address> addressValidator = Yavi.schema()
            ._string("street", c -> c.notBlank())
            ._string("city", c -> c.notBlank())
            .fromMap(Address::new);

    static final ObjectInputValidator<User> userValidator = Yavi.schema()
            ._string("email", c -> c.notBlank().email())
            ._object("address", addressValidator)
            ._list("roles", Yavi._string(c -> c.notBlank()))
            .fromMap(User::new);

    public static void main(String[] args) {
        // The street is blank and the second role is blank.
        ConstraintViolations violations = userValidator
                .validate(Map.of("email", "yavi@example.com", "address", Map.of("street", "", "city", "Tokyo"), "roles",
                        List.of("admin", " ")))
                .errors();
        for (ConstraintViolation violation : violations) {
            System.out.println(violation.name() + " " + violation.messageKey());
        }
    }

}
```
<!-- run: expected output
address.street charSequence.notBlank
roles[1] charSequence.notBlank
-->

## Maps

`_map(name, valueValidator)` validates every value of a map. The keys are data, not property names, so a violation is located under the key (`scores.math`):

```java
ObjectInputValidator<Exam> examValidator = Yavi.schema()
        ._string("student")
        ._map("scores", Yavi._integer(c -> c.greaterThanOrEqual(0).lessThanOrEqual(100)),
                c -> c.notEmpty())
        .fromMap(Exam::new);
```

A key that is not a string is reported with `object.type`. The constraints of `_map` are checked on the validated values and reported on the property.

## Embedded objects

`_embedded(validator)` reads the same map as the properties. It builds an object from the columns of several tables in the row of a JOIN:

```java
ObjectInputValidator<UserName> userNameValidator = Yavi.schema()
        ._string("first_name", c -> c.notBlank())
        ._string("last_name", c -> c.notBlank())
        .fromMap(UserName::new);

ObjectInputValidator<Department> departmentValidator = Yavi.schema()
        ._string("dept_name", c -> c.notBlank())
        ._string("dept_code", c -> c.notBlank())
        .fromMap(Department::new);

ObjectInputValidator<Employee> employeeValidator = Yavi.schema()
        ._integer("id")
        ._embedded(userNameValidator)              // first_name, last_name
        ._embedded(departmentValidator).nullable() // null if dept_name and dept_code have no value
        .fromMap(Employee::new);
```

* The properties of an embedded validator are properties of the embedding one. They are described, are not unknown to `rejectingUnknownProperties()`, and a name defined twice is rejected when the validator is built.
* An embedded validator with `optional()`, `nullable()` or `defaultValue(...)` is given `null` when none of its properties has a value.
* Embedding is also the way to read more than 16 keys.
* A lambda may be embedded too. The properties it reads are unknown, so the validator can then neither reject unknown properties nor read the rest.

## Unknown properties

A key that no property is defined for is ignored. `rejectingUnknownProperties()` reports it with `object.unknownProperty` and writes `additionalProperties: false` in the JSON Schema:

```java
ObjectInputValidator<Signup> signupValidator = Yavi.schema()
        ._string("email", c -> c.notBlank().email())
        .fromMap(Signup::new)
        .rejectingUnknownProperties();
```

The setting applies to that map only, not to the nested ones. It catches a typo in an optional property. A form that adds a hidden field, such as a checkbox, needs a property or the rest for that key.

## Rest properties

`_rest(valueValidator)` validates the keys that no property is defined for and gives them to the constructor as a map. `_rest()` takes the values as they are:

```java
record Item(String name, Map<String, String> attrs) {}

ObjectInputValidator<Item> itemValidator = Yavi.schema()
        ._string("name", c -> c.notBlank())
        ._rest(Yavi._string(c -> c.notBlank()))
        .fromMap(Item::new);
```

* `_rest` is the last property of a schema, and a schema with `_rest` has no `rejectingUnknownProperties()`, because no key is unknown.
* The rest is an empty map if there is no other key, never `null`, so it takes `recover(...)` only: `_rest().nullable()` does not compile.
* A violation of the rest is located under its key.

## Schemas known at run time

`Yavi.dynamicSchema()` describes properties that come from configuration or a database, such as the questions of a survey or custom fields. Its validator produces a map of the validated values by their names:

```java
record Question(String id, String title, boolean required, int maxLength) {}

DynamicSchema<String> schema = Yavi.dynamicSchema();
for (Question question : survey.questions()) {
    StringValidator<String> answer = Yavi._string(c -> c.notBlank().lessThanOrEqual(question.maxLength()));
    schema = question.required() ? schema.property(question.id(), answer).label(question.title())
            : schema.property(question.id(), answer.defaultValue("")).label(question.title());
}
ObjectInputValidator<Map<String, String>> answersValidator = schema.build();

answersValidator.validate(Map.of("q1", "yavi")); // {q1=yavi}
```

A schema is immutable: `property(name, validator)` returns a new one. The validator is used under the name of the property, and the value is required unless the validator accepts `null`. The modifiers are `label`, `required(message)`, `typeMessage` and `presence()`, with the staged types of `Yavi.schema()`. `rest(valueValidator)` validates the keys that no property is defined for and adds them to the map. The result has `rejectingUnknownProperties()`, `readingParameters()` and `description()`, and it can be a property of another schema.

## Recursive structures

`ValueValidator.recursive(self -> ...)` builds a validator from a reference to itself, for a structure that contains itself:

```java
record Comment(String body, List<Comment> replies) {}

ObjectInputValidator<Comment> commentValidator = ValueValidator.recursive(self -> Yavi.schema()
        ._string("body", c -> c.notBlank())
        ._list("replies", self).defaultValue(List.of())
        .fromMap(Comment::new));
// a violation: replies[0].replies[0].body
```

`ValueValidator.lazy(() -> validator)` refers to a validator that is not built yet, for validators that refer to each other. Give the reference a name, `lazy("comment", ...)` or `recursive("comment", ...)`, when the description is written with `$defs`.

The depth of a recursive structure is the depth of the input. YAVI does not impose a limit, so a hostile document needs a limit of its own, such as a maximum depth in the parser.


---

# FILE: references/optional-and-defaults.md

# Optional and Default Values

A property of `Yavi.schema()` is required. This page describes the modifiers that accept an absent key or `null`, that produce a default or a fallback, and that make a key required again.

## Absent keys and explicit null

When a schema reads a map, request parameters or a JSON tree, an absent key is validated like `null`. For a required property:

| Input | Violation |
| --- | --- |
| The key is absent | `object.required`: `"name" is required` |
| The value is explicitly `null` | `object.notNull`: `"name" must not be null`, or the violation of a constraint that rejects `null` |

A property that accepts `null` accepts an absent key too. A partial update, where an absent key means "leave unchanged" and `null` means "clear", is written with `presence()`, which tells the two apart.

## Accepting null

`nullable()`, `optional()` and `defaultValue(...)` apply to the last added property:

```java
record User(String email, @Nullable String nickname, Optional<String> bio, Integer age) {}

ObjectInputValidator<User> userValidator = Yavi.schema()
        ._string("email", c -> c.notBlank().email())
        ._string("nickname", c -> c.lessThanOrEqual(20)).nullable()
        ._string("bio", c -> c.lessThanOrEqual(500)).optional()
        ._integer("age", c -> c.greaterThanOrEqual(0)).defaultValue(20)
        .fromMap(User::new);
```

* `nullable()` produces `@Nullable String` and is the only modifier that produces `null`.
* `optional()` produces `Optional<String>`: `Optional.empty()` for an absent key or `null`.
* `defaultValue(20)` produces the default for an absent key or `null`.

The program below sends only `name`, so it prints the created `User` with `nickname` as `null`, `bio` as `Optional.empty()` and the default `age`, and then the violations of an input that leaves `name` out and makes `age` negative.

```java runnable
import java.util.Map;
import java.util.Optional;

import am.ik.yavi.core.ConstraintViolation;
import am.ik.yavi.core.ConstraintViolations;
import am.ik.yavi.input.ObjectInputValidator;
import am.ik.yavi.validator.Yavi;

public class Main {

    record User(String name, String nickname, Optional<String> bio, Integer age) {
    }

    static final ObjectInputValidator<User> validator = Yavi.schema()
            ._string("name", c -> c.notBlank())
            ._string("nickname", c -> c.lessThanOrEqual(20)).nullable()
            ._string("bio", c -> c.lessThanOrEqual(500)).optional()
            ._integer("age", c -> c.greaterThanOrEqual(0)).defaultValue(20)
            .fromMap(User::new);

    public static void main(String[] args) {
        // Only "name" is sent: nickname is null, bio is empty and age takes its default.
        User user = validator.validated(Map.of("name", "yavi"));
        System.out.println(user);

        // "name" is missing and "age" is out of range.
        ConstraintViolations violations = validator.validate(Map.of("age", -1)).errors();
        for (ConstraintViolation violation : violations) {
            System.out.println(violation.name() + " " + violation.messageKey() + ": " + violation.message());
        }
    }

}
```
<!-- run: expected output
User[name=yavi, nickname=null, bio=Optional.empty, age=20]
name object.required: "name" is required
age numeric.greaterThanOrEqual: "age" must be greater than or equal to 0
-->

The function given to `fromMap` must accept the produced type. With NullAway or Kotlin, a `nullable()` property requires a `@Nullable` parameter (in Kotlin, `String?`), and `optional()` requires an `Optional<String>`.

A modifier chain in which one modifier has no effect does not compile: `.nullable().optional()`, `.defaultValue(1).nullable()`, `.defaultValue(1).recover(2)`. A property added with a validator that already accepts `null`, such as `_integer(Yavi._integer("page", c -> c.positive()).defaultValue(1))`, takes no second modifier that accepts `null`.

`notNull()` is still the way to give the violation of `null` another message. `isNull()` needs `nullable()`: `._string("id", c -> c.isNull()).nullable()` accepts only `null`, whereas without `nullable()` no value is valid.

## Presence

`presence()` reads a property as a `Presence`, which is one of `Present(value)`, `PresentNull` and `Absent`. It is the modifier for a PATCH request or a JSON Merge Patch, where an absent key leaves a value unchanged and `null` clears it:

```java
record ProfilePatch(Presence<String> nickname, Presence<@Nullable String> bio) {}

ObjectInputValidator<ProfilePatch> patchValidator = Yavi.schema()
        ._string("nickname", c -> c.lessThanOrEqual(50)).presence()
        ._string("bio", c -> c.lessThanOrEqual(500)).nullable().presence()
        .fromMap(ProfilePatch::new);

ProfilePatch patch = patchValidator.validated(Map.of("bio", "Hello")); // nickname is Absent
patch.nickname().ifPresent(profile::setNickname); // not called
profile.setBio(patch.bio().orElse(profile.getBio())); // null if the key is null
```

* An absent key is `Absent` and is not validated, so the property is never required.
* A present key is validated as without `presence()`. An explicit `null` is a violation unless the property is `nullable()`, which produces `PresentNull`.
* `presence()` is the last modifier. `nullable()`, `defaultValue(...)` and `recover(...)` are written before it and apply to the value of a present key.
* `presence()` is not available on an `_embedded` or `_rest` property, which is not read from a key, or after `optional()`, whose `Optional` would be wrapped.
* With `apply(f)`, the argument itself is a `Presence`; `liftPresence()` is the combinator for a single-value validator.
* In request parameters, a parameter with an empty value (`bio=`) is present and `null`.

## Default values

`defaultValue(value)` produces the value for an absent key and for `null`. The default is not validated; it is the value of the property.

```java
._integer("page", c -> c.greaterThanOrEqual(1)).defaultValue(1)
._boolean("includeArchived").defaultValue(false)
._list("tags", Yavi._string(c -> c.notBlank())).defaultValue(List.of())
```

A default value is of the type of the property, so a default that is `null` is written with `nullable()`. `defaultValue(null)` of a value that is never `null`, such as the value of constraints, a list, a map or an `Optional`, is rejected with a `NullPointerException` when the schema is built.

## Recovery

`recover(fallback)` makes a property never fail: the fallback is produced for `null` and for a value that is invalid. When the property is read from a map, request parameters or a JSON tree, a value that does not represent its type produces the fallback too. `recoverWith(violations -> ...)` computes the fallback from the violations, for example to log them; it is given no violation for `null`.

```java
._integer("size", c -> c.greaterThanOrEqual(1).lessThanOrEqual(100)).recover(20)
._integer("page", c -> c.greaterThanOrEqual(0)).recover(0)
```

`recover` after `optional()` or `nullable()` recovers an invalid value. `optional()`, `nullable()` or `defaultValue(...)` after `recover(...)` changes what `null` produces. A recovery value that is `null` is written as `.nullable().recover(null)`.

## Requiring a key or rejecting null

A contract that is not a partial update often accepts only one of the two states. `required()` and `rejectingNull()` say which, without changing the type of the value:

```java
record Account(@Nullable Instant deletedAt, Optional<String> bio, int page) {}

ObjectInputValidator<Account> accountValidator = Yavi.schema()
        ._instant("deletedAt").nullable().required()      // must be sent, as null if there is none
        ._string("bio").optional().rejectingNull()        // may be omitted, a text if it is sent
        ._integer("page").defaultValue(1).rejectingNull() // 1 only if omitted
        .fromMap(Account::new);

accountValidator.validate(Map.of());                                  // "deletedAt" is required
accountValidator.validate(Collections.singletonMap("deletedAt", null)); // deletedAt=null, bio=Optional.empty, page=1
```

They are written after `optional()`, `nullable()`, `defaultValue(...)` or `recover(...)`. Typed arguments (`apply`) have no absent state, so `null` is validated there as without them.

| Property | An absent key | An explicit `null` |
| --- | --- | --- |
| `_string("x")` | `object.required` | `object.notNull` |
| `.nullable()`, `.optional()`, `.defaultValue(...)`, `.recover(...)` | accepted | accepted |
| followed by `.required()` | `object.required` | accepted |
| followed by `.rejectingNull()` | accepted | `object.notNull` |
| `.presence()` | `Absent` | validated by the property |

## Nullness and type changes

The type of a validated value tells whether it can be `null`:

| Modifier | Produced type |
| --- | --- |
| none | `String` |
| `nullable()` | `@Nullable String` |
| `optional()` | `Optional<String>` |
| `defaultValue(v)` | `String` |
| `recover(v)` | `String`, or `@Nullable String` for `recover(null)` on a nullable value |
| `presence()` | `Presence<String>`, or `Presence<@Nullable String>` after `nullable()` |

With a nullness checker that reads JSpecify (NullAway, Kotlin), `fromMap(User::new)` does not compile if a `nullable()` argument is given to a parameter that is not `@Nullable`. This is the check that the 0.18 model adds: a forgotten `nullable()` is a compile error at the call site, not a `NullPointerException` at run time.

## Behavior summary

* An absent key is validated like `null` and is never passed to the constructor as a missing value.
* A modifier that accepts `null` decides what is produced: `Optional.empty()`, `null` or the default.
* `required()` rejects an absent key and `rejectingNull()` rejects an explicit `null`; neither changes the type.
* `presence()` is for the two states of a partial update and is the last modifier of a property.
* A chain in which a modifier has no effect does not compile.


---

# FILE: references/result-handling.md

# Handling Results

`validate(...)` returns a `Validated<X>`, which holds either the created object or the `ConstraintViolations`. All violations are accumulated, so an invalid input reports every failed constraint at once.

```java
switch (userValidator.validate(map)) {
    case Validated.Valid<User>(User user) -> save(user);
    case Validated.Invalid<User>(ConstraintViolations violations) ->
        violations.forEach(violation -> report(violation.name(), violation.message()));
}
```

## Validated and exhaustive switches

`Validated` is a sealed interface of the records `Valid` and `Invalid`, so a result is handled with an exhaustive `switch` and no `default` branch. `Arguments1` to `Arguments16` are records too: `case Validated.Valid(Arguments2(var name, var age))`.

`isValid()`, `value()` and `errors()` are available where a switch is not convenient. `value()` of a failed result and `errors()` of a successful result throw.

A failed result prints as it reads, with the pointer, the message and the message key. The violated value is not printed unless the message shows it.

```java
userValidator.validate(Map.of("email", "invalid", "age", 300)).toString();
// Invalid[errors=[/email: "email" must be a valid email address (charSequence.email), ...]]
```

## validated() and ConstraintViolationsException

`validated(...)` returns the object and throws a `ConstraintViolationsException` if the input is invalid. The exception holds the violations:

```java
try {
    User user = userValidator.validated(map);
}
catch (ConstraintViolationsException e) {
    ConstraintViolations violations = e.violations();
}
```

Use `validated(...)` at a boundary where an invalid input is exceptional. A form or an API response handles `Validated` itself. A violation has its own `violatedValue()`, which is not in a `ViolationDetail`; see [Violations](violations.md).

## Transforming a result

`map` transforms a successful value and keeps a failure. `flatMap` continues with another `Validated` and accumulates the violations of both:

```java
Validated<Order> order = userValidator.validate(map)
        .map(User::toOrder)
        .flatMap(orderService::place);
```

`fold(errorsMapper, mapper)` handles both cases in one expression, and `bimap`, `mapErrors` and `mapError` transform the failure. The functions of `map` and `flatMap` are not applied to a failed result.

## Success and failure records

A hand-written step creates a result with `Validated.successWith(value)` or `Validated.failureWith(...)`. A failure is built from a `ViolationMessage`:

```java
return Validated.failureWith(
        ViolationMessage.of("order.outOfStock", "\"{0}\" exceeds the stock of {1}", "stock"),
        quantity, locale, stock);
```

`Validated.failureWith(message, args...)` and `ConstraintViolation.of(message, args...)` create a violation of `Locale.getDefault()` without a violated value. A function given to `flatFromMap` or `flatApply` is not given the locale: the violations it returns are reported with the locale of the validation, as `localizedWith(locale)` does elsewhere.

## Thread safety

Validators built with `Yavi.schema()`, `fromMap` or `apply` are immutable and may be shared and reused concurrently. A `Validated`, a `ConstraintViolations` and a `ConstraintViolation` are immutable values; the collections they return are unmodifiable. A `MessageFormatter` is called during validation and when a message is formatted, so it must be thread-safe if the validator is shared. A lambda validator that captures mutable state is not thread-safe by itself.


---

# FILE: references/unions.md

# Unions

A union accepts one of several shapes. YAVI provides a validator that tries alternatives and a validator that selects one by a discriminator.

## Alternatives

`ValueValidator.anyOf(a, b)` tries the alternatives in order and produces the value of the first one that is valid:

```java
ValueValidator<Object, Object> identifier = ValueValidator.anyOf(
        Yavi._string(c -> c.uuid()).untyped(),
        Yavi._integer(c -> c.positive()).untyped());
```

Alternatives of different input types are made untyped with `untyped()`. The alternatives share the output type; a common supertype such as a sealed interface is declared for the union, and each alternative produces one of its subtypes.

A union can be a property, an element or the root validator:

```java
ObjectInputValidator<Contact> contactValidator = Yavi.schema()
        ._object("contact", ValueValidator.anyOf(emailContact, phoneContact))
        .fromMap(contact -> contact);
```

An alternative does not need its own name. The union reports its violation under the place where it is used (`contact`).

## Discriminated unions

`DiscriminatedUnionValidator` selects the alternative by the value of a key. This is the validator for the subtypes of a sealed interface:

```java
ValueValidator<Map<String, Object>, Shape> shapeValidator = DiscriminatedUnionValidator.<Shape>of("type")
        .when("circle", Yavi.schema()._integer("radius", c -> c.positive()).fromMap(Circle::new))
        .when("square", Yavi.schema()._integer("side", c -> c.positive()).fromMap(Square::new));
```

* Only the selected alternative is validated. The keys of the other alternatives are not required.
* An absent discriminator is reported with `object.required` and an unexpected value with `object.oneOf`.
* The discriminator is read from its own key and is not a property of the alternative.
* A discriminated union is embedded in another schema in the same way as an object validator, and it can be lifted to a list with `liftList()` or `prefixed(name)`.

`DiscriminatedUnionValidator.Reversible` writes the selected object back with its discriminator:

```java
ObjectInputValidator.Reversible<Circle> circleValidator = Yavi.reversibleSchema()
        ._integer("radius", c -> c.positive())
        .fromMapReversible(Circle::new, Circle::radius);
ObjectInputValidator.Reversible<Square> squareValidator = Yavi.reversibleSchema()
        ._integer("side", c -> c.positive())
        .fromMapReversible(Square::new, Square::side);

DiscriminatedUnionValidator.Reversible<Shape> reversible =
        DiscriminatedUnionValidator.<Shape>of("type")
                .when("circle", Circle.class, circleValidator)
                .when("square", Square.class, squareValidator);

reversible.toMap(new Circle(1.5)); // {type=circle, radius=1.5}
```

## Reporting violations

When no alternative of `anyOf` matches, the result is one violation with the key `object.anyOf`. The violation is a `ConstraintViolation.NoAlternativeMatched`, and its `alternatives()` returns one `ConstraintViolations` per alternative, in the order the alternatives were tried:

```java
ConstraintViolations violations = contactValidator
        .validate(Map.of("contact", Map.of("kind", "email", "value", "x")))
        .errors();

violations.messagesByName();
// {contact=["contact" must satisfy at least one of the 2 alternatives]}

if (violations.get(0) instanceof ConstraintViolation.NoAlternativeMatched unmatched) {
    unmatched.alternatives().get(0).messagesByName();
    // {contact.value=["contact.value" must be a valid email address]}
    unmatched.alternatives().get(1).messagesByName();
    // {contact.kind=["contact.kind" must be equal to phone], ...}
}
```

The program below builds the union, validates a value that matches neither alternative and prints the violation name, its message and the violations of each alternative.

```java runnable
import java.util.Map;

import am.ik.yavi.core.ConstraintViolation;
import am.ik.yavi.core.ConstraintViolations;
import am.ik.yavi.core.ValueValidator;
import am.ik.yavi.input.ObjectInputValidator;
import am.ik.yavi.validator.Yavi;

public class Main {

    sealed interface Contact permits EmailContact, PhoneContact {
    }

    record EmailContact(String value) implements Contact {
    }

    record PhoneContact(String value) implements Contact {
    }

    record Envelope(Contact contact) {
    }

    static final ObjectInputValidator<EmailContact> emailContact = Yavi.schema()
            ._string("value", c -> c.email())
            .fromMap(EmailContact::new);

    static final ObjectInputValidator<PhoneContact> phoneContact = Yavi.schema()
            ._string("value", c -> c.pattern("\\+[0-9]+"))
            .fromMap(PhoneContact::new);

    static final ValueValidator<Map<String, Object>, Contact> contact = ValueValidator.anyOf(emailContact,
            phoneContact);

    static final ObjectInputValidator<Envelope> validator = Yavi.schema()
            ._object("contact", contact)
            .fromMap(Envelope::new);

    public static void main(String[] args) {
        // "x" is neither an email address nor a phone number.
        ConstraintViolations violations = validator.validate(Map.of("contact", Map.of("value", "x"))).errors();
        ConstraintViolation violation = violations.get(0);
        System.out.println(violation.name() + " " + violation.messageKey());
        System.out.println(violation.message());
        if (violation instanceof ConstraintViolation.NoAlternativeMatched unmatched) {
            System.out.println("alternatives: " + unmatched.alternatives().size());
            for (ConstraintViolations alternative : unmatched.alternatives()) {
                alternative.forEach(v -> System.out.println(v.name() + " " + v.messageKey()));
            }
        }
    }

}
```
<!-- run: expected output
contact object.anyOf
"contact" must satisfy at least one of the 2 alternatives
alternatives: 2
contact.value charSequence.email
contact.value charSequence.pattern
-->

The violations of the alternatives are not mixed into the top-level list, because nothing there would tell which alternative a violation belongs to. A client that shows a specific message can pick the alternative with the fewest violations:

```java
ConstraintViolations closest = unmatched.alternatives().stream()
        .min(Comparator.comparingInt(ConstraintViolations::size))
        .orElseThrow();
```

In JSON, `violations.details()` returns a `ViolationDetail.NoAlternativeMatched`, whose `alternatives` holds the details of each alternative. Any other detail is a `ViolationDetail.Simple`.

A discriminated union reports the violations of the selected alternative directly, under the names of its properties. An absent or unknown discriminator is a single violation on the union, not a list of alternatives.


---

# FILE: references/using-yavi.md

# Object Validation

`am.ik.yavi.builder.ValidatorBuilder` builds a `Validator<T>` that validates an object that already exists. A property of the object is valid when it is `null` unless a constraint such as `notNull()` rejects it; this is the difference from a property of `Yavi.schema()`.

```java
Validator<User> validator = ValidatorBuilder.<User>of()
        .constraint(User::name, "name", c -> c.notNull().lessThanOrEqual(20))
        .constraint(User::email, "email", c -> c.notNull().greaterThanOrEqual(5).lessThanOrEqual(50).email())
        .constraint(User::age, "age", c -> c.greaterThanOrEqual(0).lessThanOrEqual(200))
        .build();

ConstraintViolations violations = validator.validate(user);
```

Use the typed method of a constraint rather than `constraint` when the type of the property would be ambiguous. `_string`, `_integer`, `_bigDecimal` and the other methods take a `Function` that reads the property, so a record accessor, a getter or a lambda works.

```java
Validator<User> validator = ValidatorBuilder.<User>of()
        ._string(User::name, "name", c -> c.notNull().lessThanOrEqual(20))
        ._string(User::email, "email", c -> c.notNull().email())
        ._integer(User::age, "age", c -> c.greaterThanOrEqual(0))
        .build();
```

A validator is thread-safe and may be reused. All violations are accumulated by default; see [Fail-fast mode](#fail-fast-mode) to stop at the first one.

## Nested objects

`nest` applies a validator to a nested object. A nested validator can be passed in, or defined inline.

```java
Validator<Address> addressValidator = ValidatorBuilder.<Address>of()
        .nest(Address::country, "country", countryValidator)
        .nest(Address::city, "city",
                b -> b._string(City::name, "name", c -> c.notBlank().lessThanOrEqual(100)))
        .build();
```

The violations of a nested object are located under its name (`country.name`). `nestIfPresent` validates a nested object only when it is not `null`.

```java
Validator<Order> validator = ValidatorBuilder.<Order>of()
        .nestIfPresent(Order::customer, "customer", customerValidator)
        .build();
```

## Collection, map and array elements

`forEach` applies a validator to every element of a collection, map value or array. The name of an element is its index in the violation name (`histories[0].revision`).

```java
Validator<Histories> validator = ValidatorBuilder.<Histories>of()
        .forEach(Histories::value, "histories", historyValidator)
        .build();
```

An inline validator and `forEachIfPresent` are available as for nested objects.

```java
Validator<Histories> validator = ValidatorBuilder.<Histories>of()
        .forEach(Histories::value, "histories",
                b -> b._integer(History::revision, "revision", c -> c.greaterThanOrEqual(1)))
        .build();
```

Only map values are validated out of the box. To validate map keys, read them as a collection:

```java
Validator<CodeMap> validator = ValidatorBuilder.<CodeMap>of()
        .forEach(codeMap -> codeMap.asMap().keySet(), "codeMap",
                b -> b._string(k -> k, "value", c -> c.notEmpty()))
        .build();
```

A `ValidatorBuilder` with a message key separator other than `.` uses it in the names under `forEach` too:

```java
new ValidatorBuilder<Order>("/")
        .forEach(Order::addresses, "addresses", b -> b._string(Address::street, "street", c -> c.notBlank()))
        .build();
// addresses[0]/street
```

The program below nests a validator and applies an element validator, then prints the violation names.

```java runnable
import java.util.List;

import am.ik.yavi.builder.ValidatorBuilder;
import am.ik.yavi.core.ConstraintViolations;
import am.ik.yavi.core.Validator;

public class Main {

    record History(int revision) {
    }

    record Histories(List<History> value) {
    }

    static final Validator<History> historyValidator = ValidatorBuilder.<History>of()
            .constraint(History::revision, "revision", c -> c.greaterThanOrEqual(1))
            .build();

    static final Validator<Histories> validator = ValidatorBuilder.<Histories>of()
            .forEach(Histories::value, "histories", historyValidator)
            .build();

    public static void main(String[] args) {
        ConstraintViolations violations = validator
            .validate(new Histories(List.of(new History(0), new History(1), new History(-1))));
        System.out.println("violations: " + violations.size());
        violations.forEach(v -> System.out.println("- " + v.name() + ": " + v.message()));
    }
}
```
<!-- run: expected output
violations: 2
- histories[0].revision: "histories[0].revision" must be greater than or equal to 1
- histories[2].revision: "histories[2].revision" must be greater than or equal to 1
-->

## Conditional constraints

`constraintOnCondition` applies a validator only when a condition holds. A condition receives the target and the `ConstraintContext` of the validation call, so it can read the attributes of the request.

```java
Validator<User> validator = ValidatorBuilder.<User>of()
        .constraintOnCondition((user, context) -> "IT".equals(context.attribute("country").value()),
                b -> b._string(User::taxId, "taxId", c -> c.notBlank()))
        .build();

ConstraintContext context = ConstraintContext.from(Map.of("country", "IT"));
ConstraintViolations violations = validator.validate(user, context);
```

`ConstraintCondition.hasAttribute` and `ConstraintCondition.hasAttributeWithValue` are shortcuts for the common attribute checks.

```java
Validator<User> validator = ValidatorBuilder.<User>of()
        .constraintOnCondition(ConstraintCondition.hasAttributeWithValue("country", "IT"),
                b -> b._string(User::taxId, "taxId", c -> c.notBlank()))
        .build();
```

## Constraint groups

A `ConstraintGroup` is a `ConstraintContext` that carries a name. Constraints added with `constraintOnGroup` are applied only when that group is validated.

```java
enum Group implements ConstraintGroup {

    CREATE, UPDATE

}

Validator<User> validator = ValidatorBuilder.<User>of()
        .constraintOnGroup(Group.CREATE, b -> b._integer(User::id, "id", c -> c.isNull()))
        .constraintOnGroup(Group.UPDATE, b -> b._integer(User::id, "id", c -> c.notNull()))
        .build();

ConstraintViolations violations = validator.validate(user, Group.CREATE);
```

A group can be created without an enum, with `ConstraintGroup.of("CREATE")`. A constraint without a group is applied for every group, and `ConstraintGroup.DEFAULT` is used when `validate` is given no group. Groups match by name.

## Cross-field validation

`constraintOnTarget` adds a rule that spans several properties. The violation is reported under the given name.

```java
Validator<Range> validator = ValidatorBuilder.<Range>of()
        ._integer(Range::from, "from", c -> c.greaterThan(0))
        ._integer(Range::to, "to", c -> c.greaterThan(0))
        .constraintOnTarget(range -> range.to() > range.from(), "to", "to.isGreaterThanFrom",
                "\"to\" must be greater than \"from\"")
        .build();
```

The rule is evaluated after the properties. A `CustomConstraint<T>` can supply the predicate and the message too; see [Custom Constraints](custom-constraints.md).

## Overriding messages

`message` replaces the message of the constraint it follows. `{0}` is the name of the property, the other placeholders are the arguments of the constraint, and the last argument is the value that violated it.

```java
Validator<User> validator = ValidatorBuilder.<User>of()
        ._string(User::name, "name", c -> c.notNull().message("{0} is required!")
                .greaterThanOrEqual(1).message("{0} is too small!")
                .lessThanOrEqual(20).message("{0} is too large!"))
        .build();
```

A text given to `message(String)` is the message. A `MessageFormatter` does not replace it with the message of a resource bundle; it only substitutes the arguments, and the violation keeps its message key. To let a bundle localize a message of your own, give it a key:

```java
c -> c.notBlank().message(ViolationMessage.of("user.name.notBlank", "Enter your name"))
```

Install a `MessageFormatter` on the builder to format the messages of the other constraints.

```java
Validator<User> validator = ValidatorBuilder.<User>of()
        .messageFormatter(new MessageSourceMessageFormatter(messageSource::getMessage))
        ._string(User::name, "name", c -> c.notBlank())
        .build();
```

## Fail-fast mode

`failFast(true)` returns from the validation at the first violation. The mode is passed down to nested, element and conditional validators.

```java
Validator<User> validator = ValidatorBuilder.<User>of()
        ._string(User::name, "name", c -> c.notNull().lessThanOrEqual(20))
        ._string(User::email, "email", c -> c.notNull().email())
        .failFast(true)
        .build();

Validator<User> failFastValidator = validator.failFast(true);
boolean failFast = failFastValidator.isFailFast();
```

## Conflicting constraint names

`conflictStrategy(ConflictStrategy)` decides what happens when the same constraint name is added more than once. The default, `ConflictStrategy.NOOP`, appends the new constraints. `ConflictStrategy.OVERRIDE` removes the existing ones.

```java
Validator<User> validator = ValidatorBuilder.<User>of()
        .conflictStrategy(ConflictStrategy.OVERRIDE)
        ._string(User::name, "name", c -> c.notNull())
        ._string(User::name, "name", c -> c.notBlank()) // replaces the previous "name" constraint
        .build();
```

A custom strategy mutates the list of existing predicates; the new predicate is appended after it returns.

## Handling violations

`validate` returns a `ConstraintViolations`, which is a `List<ConstraintViolation>` and is empty when the object is valid. Iterate it to read each violation.

```java
for (ConstraintViolation violation : violations) {
    String name = violation.name();          // tags[1]
    String key = violation.messageKey();     // charSequence.notBlank
    String message = violation.message();
    Object[] args = violation.args();
    Object value = violation.violatedValue();
    String pointer = violation.pointer();    // /tags/1
}
```

`ConstraintViolation` has no name when the value itself is validated; its message then says "The value".

`messagesByName` and `messagesByPointer` return the messages in the shape a form or an API response needs, and `details` returns records that a JSON library serializes as they are.

```java
Map<String, List<String>> byName = violations.messagesByName();
Map<String, List<String>> byPointer = violations.messagesByPointer();

List<ViolationDetail> details = violations.details();
// [{"name": "items[1].quantity", "pointer": "/items/1/quantity",
//   "messageKey": "numeric.lessThanOrEqual", "message": "...", "params": {"max": 99}}]
```

A `ViolationDetail` is a sealed interface of records. Its accessors are `name()`, `pointer()`, `messageKey()`, `message()` and `params()`; the positional arguments are on `ConstraintViolation#args()`. The value that violated the constraint is not in a detail, which makes a detail safe to return. `details()` returns an unmodifiable list.


---

# FILE: references/validating-arguments.md

# Argument Validation

An arguments validator validates the arguments of a constructor or a factory method before the object is created, so an object that does not satisfy its rules never exists.

```java
public final class Person {

    public static final Arguments3Validator<String, String, Integer, Person> validator = Yavi.schema()
            ._string("name", c -> c.notBlank().lessThanOrEqual(100))
            ._string("email", c -> c.notBlank().lessThanOrEqual(100).email())
            ._integer("age", c -> c.greaterThanOrEqual(0).lessThan(200))
            .apply(Person::new);

    private Person(String name, String email, int age) {
        // ...
    }

}
```

```java
Validated<Person> validated = Person.validator.validate("John Doe", "jdoe@example.com", 30);
```

`Arguments1Validator` to `Arguments16Validator` are available. The maximum number of arguments is 16.

`Yavi.arguments()` is the old name of `Yavi.schema()`. It still works but is deprecated; use `Yavi.schema()` for an arguments validator too. The deprecated call is the only difference: the builder and the arguments validator are the same.

```java
// deprecated
Yavi.arguments();

// current
Yavi.schema();
```

The type of the builder is `YaviSchema`; the former name `YaviArguments` is gone.

## Available argument kinds

An argument is added with a method for its type:

* `_string`
* `_boolean`
* `_short`, `_integer`, `_long`, `_float`, `_double`
* `_bigInteger`, `_bigDecimal`
* `_localDate`, `_localTime`, `_localDateTime`, `_offsetDateTime`, `_instant`, `_year`, `_yearMonth`, `_zonedDateTime`
* `_enum`
* `_object`
* `_list`, `_map`

`_object` accepts any reference type, including a collection or a map. `_list` and `_map` validate the elements or values of a list or a map.

```java
Arguments1Validator<LocalDate, LocalDate> dateValidator = Yavi.schema()
        ._localDate("date", c -> c.notNull())
        .apply(date -> date);

Arguments1Validator<List<? extends String>, List<String>> tagsValidator = Yavi.schema()
        ._list("tags", Yavi._string(c -> c.notBlank()))
        .apply(tags -> tags);
```

In 0.18 an `_enum` or `_object` argument takes the type, `_enum("role", Role.class)` and `_object("id", UUID.class)`, so that the argument can also be read from a map.

## Validating method arguments

`ArgumentsValidatorBuilder.of` validates the arguments of a method, including the receiver as the first argument. Each `_xxx` method takes an accessor for the argument position (`Arguments3::arg1` and so on) instead of a name.

```java
Arguments3Validator<UserService, String, String, User> validator = ArgumentsValidatorBuilder
        .of(UserService::createUser)
        .builder(b -> b._object(Arguments3::arg1, "userService", c -> c.notNull())
                ._string(Arguments3::arg2, "email", c -> c.email())
                ._string(Arguments3::arg3, "name", c -> c.notBlank()))
        .build();

Validated<User> validated = validator.validate(userService, "jdoe@example.com", "John Doe");
```

The `_xxx` methods of the builder take the accessor because `Arguments1Validator` to `Arguments16Validator` do not inherit from each other; use the accessor that matches the arity. This is also the form that the annotation processor generates; see [Annotation Processor](annotation-processor.md).

## Validators of a single value

A validator of one value is built with `Yavi._string`, `Yavi._integer` and the other methods of `Yavi`, or with the builder of its type.

```java
StringValidator<String> nameValidator = Yavi._string("name", c -> c.notBlank().lessThanOrEqual(100));

IntegerValidator<Integer> ageValidator = IntegerValidatorBuilder
        .of("age", c -> c.greaterThanOrEqual(0).lessThan(200))
        .build();

Validated<String> nameValidated = nameValidator.validate("John Doe");
```

`map` converts the validated value, for example to a value object. `build(Function)` of the builder of a single value does the same.

```java
StringValidator<Name> nameValidator = Yavi._string("name", c -> c.notBlank().lessThanOrEqual(100))
        .map(Name::new);
```

In 0.18 a single value is required unless `nullable()` says otherwise, and `build()` returns a type that knows how to write the value back (`StringValidator.Reversible` and the like). A declared variable of `StringValidator<String>` still compiles.

## Composing and adapting

`compose` validates a value of another type by converting it first:

```java
Arguments1Validator<Integer, Name> nameFromIdValidator = nameValidator.compose(Object::toString);
```

`wrap` turns an arguments validator into one that validates an `ArgumentsN` container, and `unwrap` turns it back:

```java
Arguments1Validator<Arguments1<String>, Name> wrapped = nameValidator.wrap();
Arguments1Validator<String, Name> unwrapped = Arguments1Validator.unwrap(wrapped);
```

`lazy()` returns a validator that produces a `Supplier` of the validated value, so the value is created only when the supplier is used.

```java
Arguments1Validator<String, Supplier<Name>> lazyValidator = nameValidator.lazy();
Supplier<Name> nameSupplier = lazyValidator.validated("John Doe");
```

`prefixed(String)` locates the violations of the value under a name. A lifted validator locates the violations of an element under its index; see [Combining Validators](combining-validators.md).

```java
ValueValidator<Iterable<? extends String>, List<Email>> emails = emailValidator.liftList();
```

`indexed(int)` is removed in 0.18. Use `prefixed(int)` on a `Validated` or a `ConstraintViolation` to put the index before the name:

```java
Validated<Email> validated = emailValidator.validate("yavi@example.com").prefixed(0);
// [0].email
```

`split` and `combine` combine validators; they are described in [Combining Validators](combining-validators.md).

## Arguments containers

`Arguments1` to `Arguments16` are immutable records that hold validated arguments. `Arguments.of(...)` creates one.

```java
Arguments3<String, String, Integer> arguments = Arguments.of("John Doe", "jdoe@example.com", 30);
String name = arguments.arg1();
String email = arguments.arg2();
Integer age = arguments.arg3();
```

`argN()` returns the argument at position `N`. `firstN()` and `lastN()` return the leading or trailing `N` arguments, and `append`, `prepend` and `reverse` return a modified copy. `toString()` returns `Arguments3[arg1=..., arg2=..., arg3=...]`.

```java
Arguments2<String, String> firstTwo = arguments.first2();
Arguments4<String, String, Integer, String> appended = arguments.append("extra");
Arguments3<Integer, String, String> reversed = arguments.reverse();
```

An `ArgumentsN` does not inherit from `ArgumentsM`, and the concrete container class is part of equality: two containers are equal only when they have the same type and the same argument values.


---

# FILE: references/value-objects.md

# Value Objects and Transforms

A validated value can be turned into a domain type before it reaches the object. This page covers `map`, reversible mapping, `preprocess` and `compose`, and the reuse of a named validator.

## Mapping a property to a value object

`map(f)` after a property maps its validated value, for example to a value object. The property is still written in place:

```java
record Email(String value) {}
record Nickname(String value) {}
record Age(int value) {}
record User(Email email, Optional<Nickname> nickname, Age age) {}

ObjectInputValidator<User> userValidator = Yavi.schema()
        ._string("email", c -> c.notBlank().email()).map(Email::new)
        ._string("nickname", c -> c.notBlank()).map(Nickname::new).optional()
        ._integer("age", c -> c.greaterThanOrEqual(0)).map(Age::new).defaultValue(new Age(20))
        .fromMap(User::new);
```

* The function is given a value that satisfies the constraints. It is never given `null`.
* The property is read, reported and described as before: its key, its type in `object.type`, its label and its JSON Schema are those of the value before `map`.
* `map` is written before the modifiers that decide what `null` produces, and those modifiers apply to the mapped value: `.optional()` produces an `Optional<Nickname>`, and a default value is a mapped value. `.optional().map(f)` and `.defaultValue(v).map(f)` do not compile.
* `label`, `typeMessage` and `withheld()` are written before or after `map`.
* The function may throw. A checked exception is wrapped by the caller; a validation that can fail is written with `flatFromMap`, described in [Cross-Field Rules](cross-field-rules.md).

## Reversible mapping

A schema that writes an object back needs the reverse function. `Yavi.reversibleSchema()` takes `map(f, g)`, where `g` returns the input of `f`:

```java
ReversibleValueValidator<String, Email> emailValidator =
        Yavi._string("email", c -> c.notBlank().email()).map(Email::new, Email::value);
```

The type tells whether a validator knows its reverse. `map(f)` is a `ValueValidator`, and `map(f, g)` is a `ReversibleValueValidator`, which a reversible schema takes and a plain schema also accepts. See [Writing an Object Back](writing-back.md) for `toMap`, `reverse` and views.

## Preprocessing

`preprocess(f)` transforms an input of the same type before the constraints. The constraints and the produced value see the transformed value, and `null` is not transformed:

```java
BigDecimalValidator<BigDecimal> priceValidator = Yavi._bigDecimal("price", c -> c.positive())
        .preprocess(BigDecimal::stripTrailingZeros);
```

A function added later is applied earlier: `validator.preprocess(f).preprocess(g)` applies `g` and then `f`. A `String` is usually transformed where its constraints are written, with `c.trim()`, `c.toLowerCase()` and the other transforms of [Defining a Schema](defining-a-schema.md).

## Composing validators

`compose(f)` adapts a validator to another input type. The function converts the input, and the result is validated as before:

```java
ValueValidator<byte[], String> tokenValidator = Yavi._string("token", c -> c.notBlank())
        .compose(bytes -> Base64.getEncoder().encodeToString(bytes));
```

The input type of a composed validator is unknown, so its description is unknown too. Give it with `untyped(type)` when it is used where the input type is required, such as the root of a document or an alternative of `anyOf`.

## Domain primitives

A value object with its own rule is defined once and used as a property, as an element or on its own:

```java
public final class Email {

    public static final StringValidator<Email> VALIDATOR =
            Yavi._string("email", c -> c.trim().notBlank().email()).map(Email::new);

    private final String value;

    private Email(String value) {
        this.value = value;
    }

    public static Email of(String value) {
        return VALIDATOR.validated(value);
    }

    public String value() {
        return value;
    }

}
```

In a schema, `._string(Email.VALIDATOR)` reads and validates the value and produces the value object, so no `map(Email::new)` is needed at the call site. The private constructor stays inside the class, and the rule is not repeated: a change to `Email.VALIDATOR` reaches every schema that uses it.

## Reusing named validators

A validator holds the name it was built with. `named(name)` returns the same validator under another name, so a rule is defined once and used under the key of each property:

```java
ObjectInputValidator<Contact> contactValidator = Yavi.schema()
        ._string(Email.VALIDATOR)                                  // the key and the name are "email"
        ._string(Email.VALIDATOR.named("backupEmail")).nullable()  // the key and the name are "backupEmail"
        ._object("replyTo", Email.VALIDATOR)                       // the same as named("replyTo")
        .fromMap(Contact::new);
```

The name replaces the one of the validator in the violations, in their messages and in `description()`. A value that has no name of its own, such as an object or a list, is located under the name (`home.street`). The combinators carry the name, so it is given before or after `map`, `nullable()` or `untyped()`.


---

# FILE: references/violations.md

# Violations

A `ConstraintViolation` is one failed rule. `ConstraintViolations` is the list of them; `messagesByName()`, `messagesByPointer()`, `details()` and `apply(...)` are the forms that a form and an API response need.

## ConstraintViolation

A violation knows where it is without parsing its name:

```java
ConstraintViolation violation = violations.get(0);
violation.name();      // tags[1]
violation.path();      // [Property[name=tags], Index[index=1]]
violation.pointer();   // /tags/1, a JSON Pointer (RFC 6901)
violation.messageKey();    // charSequence.notBlank
violation.message();       // "tags[1]" must not be blank
violation.args();          // positional message arguments
violation.params();        // arguments by name
violation.violatedValue(); // the value that failed
```

`path()` is a list of `PathSegment.Property` and `PathSegment.Index`. `label()` is the label given to the property, if any; the name, the path and the pointer are not changed by a label.

A violation is immutable. The collections it returns are unmodifiable.

## Names, paths and pointers

A name follows the structure of the input: `address.street`, `tags[0]`, `items[1].name`, `addresses[0].street`. A violation of a value without a name has the empty name and a message that says "The value". The pointer is the same path as a JSON Pointer: `/address/street`, `/tags/0`. `messagesByPointer()` uses it as the key, and it is what an `errors[].pointer` of an RFC 9457 problem detail holds.

A violation of an `anyOf` alternative is not mixed into the list. The result is one `ConstraintViolation.NoAlternativeMatched`, whose `alternatives()` holds one `ConstraintViolations` per alternative.

## ViolationDetail

`details()` returns `ViolationDetail` records that a JSON library serializes as they are:

```java
List<ViolationDetail> details = violations.details();
// [{"name": "items[1].quantity", "pointer": "/items/1/quantity", "messageKey": "numeric.lessThanOrEqual",
//   "message": "\"items[1].quantity\" must be less than or equal to 99", "params": {"max": 99}}]
```

`ViolationDetail` is a sealed interface of `ViolationDetail.Simple` and `ViolationDetail.NoAlternativeMatched`, which has `alternatives`. A `switch` over a detail needs no `default`.

`params` holds the arguments of the violation by name. The names are those of the parameters of the constraint method; what a constraint computes from the value has a name too (`actualSize`, `duplicates`, `missing`, `notAllowed`). A message of your own names its arguments from `{1}` on with `ViolationMessage.of(key, format, names...)`; without names, the violation has no parameters. The format keeps referring to the arguments by position.

| Message key | Names in `params` |
| --- | --- |
| `numeric.lessThanOrEqual` | `max` |
| `container.greaterThanOrEqual` | `min`, `actualSize` |
| `object.type` | `type` |
| `collection.unique` | `duplicates` |

The violated value is not in a detail. It may be a password or a token, and the client has sent it. `violation.args()` and `violation.violatedValue()` have it on the server.

## Message maps

```java
Map<String, List<String>> byName = violations.messagesByName();
// {"email": ["\"email\" must not be blank"], "items[1].name": ["..."]}

Map<String, List<String>> byPointer = violations.messagesByPointer();
// {"/email": [...], "/items/1/name": [...]}
```

The messages of the root are under the empty name in `messagesByName()`. Both maps are unmodifiable and hold the messages in the order of the violations.

## Immutability and alternatives

`details()` returns an unmodifiable list, and the maps and lists of `messagesByName()` and `messagesByPointer()` are unmodifiable too. Add what a response needs to a copy.

To show a specific message instead of the summary of an `anyOf`, pick the alternative with the fewest violations; the others are not shown:

```java
ConstraintViolations closest = unmatched.alternatives().stream()
        .min(Comparator.comparingInt(ConstraintViolations::size))
        .orElseThrow();
```


---

# FILE: references/writing-back.md

# Writing an Object Back

A schema names the properties of an input once. `Yavi.reversibleSchema()` builds a validator that also writes the created object back as the map it is read from, so the names are not written again for the parameters of a statement or for a form that shows a stored object.

```java
record Employee(Integer id, UserName name, Email email, Optional<String> nickname, Role role) {}

ObjectInputValidator.Reversible<Employee> employeeValidator = Yavi.reversibleSchema()
        ._integer("id")
        ._embedded(userNameValidator) // first_name, last_name
        ._string(Yavi._string("email", c -> c.notBlank().email()).map(Email::new, Email::value))
        ._string("nickname").optional()
        ._enum("role", Role.class)
        .fromMapReversible(Employee::new, Employee::id, Employee::name, Employee::email,
                Employee::nickname, Employee::role);

employeeValidator.toMap(employee);
// {id=1, first_name=Taro, last_name=Yamada, email=taro@example.com, nickname=null, role=ADMIN}
```

The following complete program builds a reversible schema, creates an object, and prints the map that `toMap` writes back and validates again.

```java runnable
import java.util.Optional;
import java.util.TreeMap;

import am.ik.yavi.input.ObjectInputValidator;
import am.ik.yavi.validator.Yavi;

public class Main {

    record User(String name, String email, Optional<String> nickname) {
    }

    static final ObjectInputValidator.Reversible<User> validator = Yavi.reversibleSchema()
            ._string("name", c -> c.notBlank())
            ._string("email", c -> c.notBlank().email())
            ._string("nickname").optional()
            .fromMapReversible(User::new, User::name, User::email, User::nickname);

    public static void main(String[] args) {
        User user = new User("Taro", "taro@example.com", Optional.empty());
        var map = new TreeMap<>(validator.toMap(user));
        System.out.println(map);
        System.out.println("round trip valid: " + validator.validate(map).isValid());
    }

}
```
<!-- run: expected output
{email=taro@example.com, name=Taro, nickname=null}
round trip valid: true
-->

## Reversible schemas

`Yavi.reversibleSchema()` has the same methods as `Yavi.schema()`, but takes a `ReversibleValueValidator` where a schema takes a `ValueValidator`: a validator that knows its reverse by its type. A validator that maps its value without saying how to go back does not compile where it is added.

* `fromMapReversible(f, accessor1, ..., accessorN)` is `fromMap(f)` with one accessor per argument, which returns the validated value of that argument from the object.
* `map(f, g)` is `map(f)` with the function that goes from the mapped value back to the input. It returns a `ReversibleValueValidator`, whose `reverse(x)` is the input that `x` is read from.
* `flatFromMapReversible` and `flatOfReversible` are the counterparts of `flatFromMap` and `of`.
* `ReversibleValueValidator.recursive(self -> ...)` is `recursive` for a structure that contains itself.
* `Yavi.reversibleDynamicSchema()` writes back the map of validated values.
* `ObjectInputValidator.ofReversible(parts, mapper)` takes a list of `ReversiblePart`: a part with its reverse and its accessor.

`toMap(x)` writes the object; `reverse(x)` writes every property, including withheld ones. The validator reads input as `fromMap` does, and is nested, embedded and read with `readingWith` and `readingParameters` as before.

## Writing nested and optional values

| Property | `toMap` |
| --- | --- |
| a value of constraints, `defaultValue`, `recover` | the value |
| an enum constant | its name |
| no value of `nullable()`, `optional()` | an entry with `null`, because a named parameter needs its key |
| no value after `rejectingNull()` | no entry |
| `presence()` | no entry for `Absent`, `null` for `PresentNull` |
| `_embedded` | in the same map; `null` for every property if it has no value |
| `_object` | a nested map |
| `_list`, `_map`, `_rest` | every element |
| `splitBy(",")` | the joined text; an empty list is `null` |
| a validator with `map(f, g)` | the result of `g` |
| `withheld()` | no entry |

A list with `splitBy` is one field of a form, so it is written as the text of that field. A pattern does not tell the text that separates the elements, so the text that joins them is given with it:

```java
ObjectInputValidator.Reversible<Feed> feedSchema = Yavi.reversibleSchema()
        ._string("title")
        ._list("urls", Yavi._string(c -> c.url())).splitBy(Pattern.compile("\\s*\\R\\s*"), "\n")
        .defaultValue(List.of())
        .fromMapReversible(Feed::new, Feed::title, Feed::urls);

feedSchema.toMap(new Feed("News", List.of("https://a.example", "https://b.example")));
// {title=News, urls="https://a.example\nhttps://b.example"}
```

`splitBy(pattern)` without the joining text does not compile in `Yavi.reversibleSchema()`. The pattern must match the text: `splitBy(Pattern.compile("\\R"), ", ")` fails when the schema is built, because the written text would not be split where it was joined.

## Views

`including` and `excluding` build a `PropertyView` that writes the chosen properties. A view is built once, and its names are checked against what the validator describes when it is built: a name that the validator does not define is an `IllegalArgumentException`, where a key removed from the map that `toMap` returns is checked by nobody.

```java
static final PropertyView<AccountUser> SUMMARY = userValidator.including("id", "name", "address.city");
static final PropertyView<AccountUser> LISTED = userValidator.excluding("address");

SUMMARY.toMap(user); // {id=1, name=Taro, address={city=Tokyo}}
LISTED.toMap(user);  // {id=1, name=Taro}
```

* A property that is not in the view has no entry; it is not written as `null`. The accessor of a property that is not written is not called.
* A view only writes. It is not a validator and not a `ReversibleValueValidator`, so it is rejected where the round trip is needed.
* A view is narrowed with its own `including` and `excluding`.
* `renaming(function)` writes a property under another key, at every depth; `renaming(path, key)` renames one property. Only the key changes. A renamed view is for a response: it is not read back and not described by the JSON Schema.

## Withheld properties

A property that must not be shown is marked where it is defined:

```java
._string("password_hash").withheld()
```

`toMap` and a view that excludes do not write it, at any depth. A view that includes writes it only if it is named. `reverse` writes every property, so the round trip holds. The same mark keeps what was sent for a password out of a form that is shown again, and makes the property `writeOnly` in a JSON Schema. It does not change what is read, and a violation still holds the rejected value.

A password is often stored in another form, as a hash the application computes. The schema of the form withholds it, and the statement is given the hash as one more parameter.

## Parameters and Forms

`ParameterTree` returns parameters in the shape of the schema, and `ParameterTree.ofValues` holds the values that a validator writes as the text of parameters. The first display of a stored object and a form that is shown again are then one code path.

```java
ParameterTree tree = stored != null ? ParameterTree.ofValues(signupSchema.toMap(stored))
        : ParameterTree.of(request.getParameterMap());
Map<String, Object> form = tree.toMap(signupSchema.description());
// {name="Taro", age="30", birthday="2000-01-02", address={city="Tokyo", street=""}}
```

* `ParameterTree.of(parameters)` takes a `Map<String, String>`, a `Map<String, List<String>>` or a `Map<String, String[]>`, in the forms that `readingParameters()` validates.
* `toMap(description)` returns a tree of `Map`, `List` and the text that was sent, for a template engine. `toParameters(description)` returns the same values under the names of the violations (`address.city`, `items[0].name`), for a `MapBindingResult` of Spring.
* A value is not trimmed, coerced or validated. A value that was not sent is an empty string; a `Boolean` that was not sent has no entry.
* A key that no property is defined for is left out. A schema with `_rest` returns the other keys.
* A withheld property is written as one that was not sent.
* `ParameterTree.parametersOf(tree)` is the reverse of `ParameterTree.of(parameters)` for any tree of `Map` and `List`.
* `ParameterTree.of(parameters, maxIndex)` gives another index limit; `ParameterTree.DEFAULT_MAX_INDEX` is 255.

## Round trip

`validator.validate(validator.toMap(x))` is `Valid(x)` for every `x` that the validator creates. `reverse` keeps the round trip for a withheld property, because it writes it. A validator that is not a `ReversibleValueValidator`, such as `map(f)` without a reverse, a lambda or `anyOf`, is rejected by the schema at compile time.

The map is new; add what a statement needs (`map.put("updated_by", user)`). A nested map cannot be bound to a statement: read the columns of a row with `_embedded`, or bind the map under the names of the violations with `ParameterTree.parametersOf`.


---

# FILE: references/contents.md

# Documentation index

Every page bundled with this skill, in the order the documentation site
presents it. Paths are relative to this file. The site publishes the same
pages, with the runnable examples live.

## Getting Started

- [Overview](index.md)
- [Introduction](introduction.md)
- [Getting Started](getting-started.md)
- [Core Concepts](concepts.md)
- [Agent Skill](agent-skill.md)

## Schemas

- [Defining a Schema](defining-a-schema.md)
- [Optional and Default Values](optional-and-defaults.md)
- [Value Objects and Transforms](value-objects.md)
- [Objects and Collections](objects-and-collections.md)
- [Unions](unions.md)
- [Cross-Field Rules](cross-field-rules.md)
- [Describing a Schema](describing-a-schema.md)

## Inputs

- [Maps and Untyped Values](input-maps.md)
- [JSON Trees](input-json.md)
- [Request Parameters and Forms](input-parameters.md)
- [Typed Arguments](input-arguments.md)

## Results

- [Handling Results](result-handling.md)
- [Violations](violations.md)
- [Messages and Localization](messages.md)

## Codecs

- [Writing an Object Back](writing-back.md)

## Integrations

- [Integration Overview](integrations.md)
- [Spring](integrations-spring.md)
- [Jackson](integrations-jackson.md)
- [Kotlin](integrations-kotlin.md)
- [NullAway](integrations-nullaway.md)

## Classic Validators

- [Object Validation](using-yavi.md)
- [Custom Constraints](custom-constraints.md)
- [Argument Validation](validating-arguments.md)
- [Combining Validators](combining-validators.md)
- [Combining Results](combining-validation-results.md)
- [Annotation Processor](annotation-processor.md)

## Reference

- [Built-in Constraints](built-in-constraints.md)
- [Migration from 0.17](migration-0.17-to-0.18.md)
- [Comparison with Zod](coming-from-zod.md)
- [Comparison with Bean Validation](coming-from-bean-validation.md)
