Joi validation return only one error message

I'm not integrating with hapi.js, but I noticed that there is a ValidationOptions object which can be passed along. Inside that object is an abortEarly option, so this should work:

Joi.validate(request, schema, { abortEarly: false }

This can also be configured as follows:

Joi.object().options({ abortEarly: false }).keys({...});

Check out these type definitions for more ValidationOptions: https://github.com/DefinitelyTyped/tsd/blob/master/typings/joi/joi.d.ts


It happens because Joi aborts early by default.

abortEarly - when true, stops validation on the first error, otherwise returns all the errors found. Defaults to true.

*EDIT: Configuration has changed in hapi 8.0. You need to add abortEarly: false to the routes config:

var server = new Hapi.Server();
server.connection({
    host: 'localhost',
    port: 8000,
    routes: {
        validate: {
            options: {
                abortEarly: false
            }
        }
    }
});

*See the Joi API documentation for more details.
*Also, see validation under Hapi Route options.

So Joi stops the validation on the first error:

var Hapi = require('hapi');
var Joi = require('joi');

var server = new Hapi.Server('localhost', 8000);

server.route({
    method: 'GET',
    path: '/{first}/{second}',
    config: {
        validate: {
            params: {
                first: Joi.string().max(5),
                second: Joi.string().max(5)
            }
        }
    },
    handler: function (request, reply) {

        reply('example');
    }
});

server.start();

server.inject('/invalid/invalid', function (res) {

    console.log(res.result);
});

Outputs:

{ statusCode: 400,
  error: 'Bad Request',
  message: 'first length must be less than or equal to 5 characters long',
  validation: { source: 'params', keys: [ 'first' ] } }

You can however configure Hapi to return all errors. For this, you need to set abortEarly to false. You can do this in server configuration:

var server = new Hapi.Server('localhost', 8000, { validation: { abortEarly: false } });

If you run the script now, you get:

{ statusCode: 400,
  error: 'Bad Request',
  message: 'first length must be less than or equal to 5 characters long. second length must be less than or equal to 5 characters long',
  validation: { source: 'params', keys: [ 'first', 'second' ] } }