const { configure, formatters } = require('indicative')
configure({
FORMATTER: formatters.JsonApi
})
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.
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.
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)
Also you can make use of a custom formatter at runtime with validate
and validateAll
methods.
validate(data, rules, null, formatters.JsonApi)
Below is the list of formatters shipped with Indicative by default.
const { formatters } = require('indicative')
formatters.Vanilla
formatters.JsonApi
The default formatter (known as vanilla) returns errors in following structure.
[
{
field: 'username',
validation: 'required',
message: 'required validation failed on username'
}
]
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
}
}
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.
This method should return the collection of errors and they are passed to the end-user. If no errors are present, return null
.