joi-errors-for-forms
In order to keep a consistent validation API in your apps, convert the error objects returned by Joi to either
- the
{ name1: text, name2: text }
schema commonly used with form UIs, or - the Mongoose schema
{ name1: { message: ..., name: 'ValidatorError', path: ..., type: ... } }
.
The Joi error messages may be replaced either for internationalization or clarity.
The package has no dependencies.
Code Examples
For the following Joi schema:
const Joi = ;const name = Joi;const password = Joi;const schema = Joiobject;const joiOptions = convert: true abortEarly: false ; const values = name: 'j' password: 'z' confirmPassword: 'z' ;
(1) Convert the Joi messages to the form UI schema, retaining the original message text.
const joiToForms = form;const convertToForms = ; Joi;
(2) Convert to the form UI schema. Replace Joi messages using Joi error types. (Recommended.)
const joiToForms = form;const convertToForms = ; Joi; { return str; } // internationalization
or convert to the Mongoose schema.
const joiToMongoose = mongoose;const convertToMongoose = ; Joi;
List of substitution tokens. Refer to Joi documentation for more information.
${key}
prop name, or label if.label('...')
was used.${value}
prop value. Its rudimentally converted to a string.${pattern}
regex value if.regex(...)
was involved in the error. Its converted to a string.${limit}
allowed length of string.${encoding}
string encoding. Could beundefined
. Its converted to a string.
Note that type
retains the Joi value in the Mongoose schema.
It is not converted to what Mongoose would return.
(3) Replace Joi messages with a generic error message.
const convertToForms = ; Joi;
(4) Replace Joi messages, by searching for substrings in Joi messages.
const convertToForms = ; Joi;
Motivation
Joi is an enterprise strength schema validator and sanitizer originally developed by Walmart.
The error object it returns, however, usually has to be reformatted for use within web/mobile apps. Its error messages may also have to be converted for internationalization or for clarity.
This package helps with both needs.
Installation
Install Nodejs.
Run npm install joi-errors-for-forms --save
in your project folder.
You can then require the package.
// ES5var joiErrorsToForms = ;var joiToForms = joiErrorsToFormsform;var joiToMongoose = joiErrorsToFormsmongoose;// or ES6;
API Reference
See Code Examples.
Tests
npm test
to run tests.
A Note on Internationalization
The options
in Joi.validate(value, schema, options, cb)
supports a
language
option
with which you can change
Joi error messages
in bulk.
You can then internationalize your field names and regex descriptions in the schema, e.g.
Joilabel
These are suitable methods to internationalize the majority of Joi error messages.
Contributors
License
MIT. See LICENSE.