Using older version of Indicative or @adonisjs/validator?. Click here to access the old version documentation.

guides

Error formatters

Error formatters are helpful when you are writing an API server following a pre-defined spec like JSON:API

Without error formatters, you have to loop over the error messages and re-shape them as per the spec followed by your API team. However, the error formatters exposes an API to collect and shape error messages within the validation lifecycle (no extra overhead).

Using formatters

By default, Indicative will use VanillaFormatter to format the validation error messages. However, you can also define a custom formatter using one of the following ways.

Global error formatter

Using the configure method, you can define a formatter to be used for all validation calls.

Per validation call

If you want to define a custom formatter for just a single validation call, then you can pass it as the 4th argument to the validate and validateAll methods.

Existing formatters

The indicative-formatters package ships with following formatters.

VanillaFormatter

Used by default and returns an array of error messages, as shown below.

JsonApiFormatter

The JsonApiFormatter returns messages as per the JSON:API spec.

Creating custom formatters

You can also create custom formatters by implementing the addError and toJSON methods on a class.

And then make use of it as follows.