⚠️ Formats validation errors in Hapi
Clone or download
Fetching latest commit…
Cannot retrieve the latest commit at this time.
Permalink
Type Name Latest commit message Commit time
Failed to load latest commit information.
.eslintrc
.gitignore
.travis.yml
README.md
format-errors.js
get-error-parts.js
get-error-parts.test.js
index.js
package-lock.json
package.json
transform-error.js

README.md

hapi-format-validation

Build Status

This Hapi plugin formats validation errors in a way that is consistent, simple, and easy to render in client-side forms. Take your typical Joi validation error reply for instance...

Before hapi-format-validation 😿

{
  statusCode: 400,
  error: 'Bad Request',
  // this message should get formatted before displaying it to a user
  message: 'child "name" fails because ["name" is not allowed to be empty]. child "email" fails because ["email" must be a valid email]',
  validation: {
    source: 'payload',
    // extra work required of the client to link these keys to error messages :(
    keys: [
      'name',
      'email'
    ]
  }
}

After hapi-format-validation 😍

{
  statusCode: 400,
  error: 'Bad Request',
  // a newline-separated string, ready-to-use if necessary
  message: '"name" is not allowed to be empty↵"email" must be a valid email',
  validation: {
    source: 'payload',
    // a simple key-value mapping of fields and their errors
    errors: {
      name: '"name" is not allowed to be empty',
      email: '"email" must be a valid email'
    }
  }
}

Installation

$ npm install --save hapi-format-validation

Usage

const FormatValidation = require('hapi-format-validation');

server.register(FormatValidation, err => {
  // server fun times
});

Options

  • stripQuotes: (optional) if true, strips double quotation marks from around the path name in error messages
  • capitalize: (optional) if true, capitalizes the first letter of each error message
  • sequelize: (optional) pass a Sequelize instance to format unique key violations (more information below)

Sequelize integration

hapi-format-validation also handles Sequelize unique key violation errors, which would otherwise be a 500 Internal Server Error. Pass your Sequelize instance (sold separately) as an option to the plugin when you register it to enable this feature.

const FormatValidation = require('hapi-format-validation');
const Sequelize = require('sequelize');

const sequelize = new Sequelize(...);

server.register(
  {
    register: FormatValidation,
    options: {sequelize}
  },
  err => {
    // do your server stuff
  }
);

Before

{
  statusCode: 500,
  error: 'Internal Server Error',
  message: 'An internal server error occurred'
}

After

{
  'statusCode': 400,
  'error': 'Bad Request',
  'message': '"username" must be unique',
  'validation': {
    'source': 'payload',
    'errors': {
      'username': '"username" must be unique'
    }
  }
}

Acknowledgements 👊