custom-joi-error
TypeScript icon, indicating that this package has built-in type declarations

1.0.0 • Public • Published

custom-joi-error Build Status Coverage Status

Customize Joi errors, by stripping quotes and setting key specific error language.

Installation

npm install custom-joi-error

Usage

Call customJoiError function with Joi's validation result as first arguments.

You can pass options as second argument.

const customJoiError = require('custom-joi-error');
/** Or with ES6+ */
import customJoiError from 'custom-joi-error';
 
const result = Joi.validate(
  { firstName: '', lastName: 10 },
  {
    firstName: Joi.string()
      .not()
      .empty()
      .label('Fist name'),
    lastName: Joi.string()
      .not()
      .empty()
      .label('Last name')
  }
);
 
if (result.error) {
  throw customJoiError(result, {
    language: {
      firstName: {
        'any.empty': 'Please enter a first name'
      }
    }
  });
}

It will return:

Error (CustomValidationError) {
  message: 'Please enter a first name, Last name must be a string',
  details: [
    {
      message: 'Please enter a first name',
      path: [ 'firstName' ],
      type: 'any.empty',
      context: {
        value: '',
        invalids: [ '' ],
        key: 'firstName',
        label: 'First name'
      },
    },
    {
      message: 'Last name must be a string',
      path: [ 'lastName' ],
      type: 'any.empty',
      context: {
        value: 10,
        key: 'lastName',
        label: 'Last name'
      },
    },
  ],
}

Options

  • stripQuotes (default: true) Remove quote from key label in error message.
  • language (default: {}) Set key specific error message, example :
{
  language: {
    name: {
      string: {
        email: 'Please enter a valid email'
      }
    }
  }
}

See Joi language file for full messages list.

Build

npm run build

Testing

npm test

Related

  • joi - Object schema validation

License

This project is licensed under the MIT license.

Readme

Keywords

Package Sidebar

Install

npm i custom-joi-error

Weekly Downloads

1

Version

1.0.0

License

MIT

Unpacked Size

10.1 kB

Total Files

10

Last publish

Collaborators

  • dimitrinicolas