Formatters

Formatters let you structure the collection of error messages. This is handy when you/your company uses certain JSON specifications and want the error messages to be structured accordingly.

Full build

The full build of Indicative uses the Vanilla formatter by default. However, you can change it using the configure method.

const { configure, formatters } = require('indicative')
configure({
  FORMATTER: formatters.JsonApi
})

Now all calls to validate and validateAll will make use of the JsonApi formatter.

Customized build

With customized build, it is straight forward to pass the formatter when creating the validator instance.

import Validator from 'indicative/builds/validator'
import { JsonApi } from 'indicative/builds/formatters'

const validator = Validator(validations, JsonApi)

Switching at runtime

Also you can make use of a custom formatter at runtime with validate and validateAll methods.

validate(data, rules, null, formatters.JsonApi)

Available formatters

Below is the list of formatters shipped with Indicative by default.

const { formatters } = require('indicative')

formatters.Vanilla
formatters.JsonApi

Vanilla

The default formatter (known as vanilla) returns errors in following structure.

[
  {
    field: 'username',
    validation: 'required',
    message: 'required validation failed on username'
  }
]

JsonApi

The JSON API formatter will return errors as follows.

{
  errors: {
    [
      {
        source: {
          pointer: 'username'
        },
        title: 'required',
        detail: 'required validation failed on username'
      }
    ]
  }
}

Creating your own

Also you can create your own formatter by defining a class with following methods.

class MyFormatter {
  constructor () {
    this.errors = []
  }

  addError (error, field, validation, args) {
    let message = error

    if (error instanceof Error) {
      validation = 'ENGINE_EXCEPTION'
      message = error.message
    }

    this.errors.push({ field, validation, message, args })
  }

  // return null if no errors are present,
  // otherwise validate will be rejected with an empty
  // error
  toJSON () {
    return this.errors.length ? this.errors : null
  }
}

addError(error, field, validation, args)

Add a new error to be returned later. If error is an instance of the Error object, then it is not a validation error but instead something bad caused validation to fail.

toJSON()

This method should return the collection of errors and they are passed to the end-user. If no errors are present, return null.