celebrate vs express-validator vs joi vs yup
Node.js Validation Libraries
celebrateexpress-validatorjoiyupSimilar Packages:

Node.js Validation Libraries

Validation libraries in Node.js are essential tools that help developers ensure the integrity and correctness of data coming into their applications, particularly from user inputs in web forms or API requests. These libraries provide mechanisms to define schemas or rules for data validation, making it easier to catch errors early in the request lifecycle. They help improve application security by preventing invalid or malicious data from being processed, thus enhancing overall application robustness. Each library offers unique features and design philosophies, catering to different developer preferences and project requirements.

Npm Package Weekly Downloads Trend

3 Years

Github Stars Ranking

Stat Detail

Package
Downloads
Stars
Size
Issues
Publish
License
celebrate01,35027.8 kB12 years agoMIT
express-validator06,243146 kB854 months agoMIT
joi021,198557 kB1914 months agoBSD-3-Clause
yup023,693270 kB2406 months agoMIT

Feature Comparison: celebrate vs express-validator vs joi vs yup

Integration

  • celebrate:

    Celebrate is designed specifically for use with Express.js, making it an ideal choice for developers who are building applications using this framework. It leverages Joi for schema validation, allowing for a straightforward integration process that enhances the middleware capabilities of Express.

  • express-validator:

    Express-validator is also tailored for Express.js, providing a set of middlewares that can be easily integrated into route definitions. Its design allows for a more modular approach, enabling developers to apply validation rules directly within their route handlers without needing to define separate schemas.

  • joi:

    Joi can be used independently of any framework, allowing for versatile integration in various Node.js applications. It is not limited to Express and can be utilized in any JavaScript context where object validation is required, making it a flexible choice for developers.

  • yup:

    Yup is primarily designed for client-side validation but can also be used in Node.js applications. It integrates well with libraries like Formik and React Hook Form, making it a popular choice for developers working with React applications.

Schema Definition

  • celebrate:

    Celebrate uses Joi for schema definitions, allowing developers to define complex validation rules in a concise and readable manner. Joi's expressive syntax makes it easy to create detailed schemas that can validate various data types and structures, including nested objects.

  • express-validator:

    Express-validator allows for a more straightforward approach to defining validation rules directly in the route handlers. While it does not provide a schema definition language like Joi, it offers a rich set of validators that can be chained together for effective validation.

  • joi:

    Joi excels in schema definition, providing a powerful and expressive API that allows developers to define intricate validation rules, including conditional validations, custom error messages, and more. Its flexibility makes it suitable for complex validation scenarios.

  • yup:

    Yup offers a similar schema definition approach to Joi, allowing for the creation of complex validation schemas with a promise-based API. It supports asynchronous validation and can handle nested objects, making it a strong choice for modern form validation.

Error Handling

  • celebrate:

    Celebrate provides detailed error messages generated by Joi, allowing developers to easily understand what validation failed and why. This feature enhances the debugging process and improves user experience by providing clear feedback on input errors.

  • express-validator:

    Express-validator generates validation errors that can be accessed in the request object, making it easy to handle and respond to validation failures. It allows for custom error messages, which can be tailored to provide better user feedback.

  • joi:

    Joi offers comprehensive error handling capabilities, providing detailed error objects that describe the validation failures. This allows developers to customize error messages and handle different validation scenarios effectively, enhancing the overall user experience.

  • yup:

    Yup also provides detailed error messages and supports asynchronous validation, allowing for more complex error handling scenarios. Its promise-based approach makes it suitable for handling validation errors in a modern JavaScript environment.

Learning Curve

  • celebrate:

    Celebrate has a moderate learning curve, especially for developers already familiar with Joi. Its integration with Express.js simplifies the process, but understanding Joi's schema syntax is essential for effective usage.

  • express-validator:

    Express-validator is relatively easy to learn, especially for those already familiar with Express.js. Its straightforward API allows developers to quickly implement validation without extensive setup, making it ideal for beginners.

  • joi:

    Joi has a steeper learning curve due to its extensive feature set and schema definition capabilities. However, once mastered, it provides powerful tools for validating complex data structures, making it worthwhile for larger projects.

  • yup:

    Yup is designed to be user-friendly, particularly for those familiar with modern JavaScript and React. Its promise-based API and clear syntax make it accessible for developers, reducing the learning curve compared to more complex validation libraries.

Asynchronous Validation

  • celebrate:

    Celebrate supports asynchronous validation through Joi, allowing for validations that require external checks, such as database queries or API calls. This feature is beneficial for scenarios where validation depends on dynamic data.

  • express-validator:

    Express-validator supports asynchronous validation but requires additional setup, as its core validators are synchronous. Developers can implement custom validators to handle asynchronous checks, but it may require more effort compared to other libraries.

  • joi:

    Joi excels in asynchronous validation, allowing developers to easily define validations that return promises. This feature is particularly useful for scenarios where validation depends on external data or conditions, providing flexibility in validation logic.

  • yup:

    Yup is built with asynchronous validation in mind, making it easy to handle validations that require promises. This feature is especially useful for form validations in React applications, where user input may need to be validated against external data.

How to Choose: celebrate vs express-validator vs joi vs yup

  • celebrate:

    Choose Celebrate if you are using Express.js and want a middleware solution that integrates seamlessly with Joi for schema validation. It is particularly useful for validating request bodies, query parameters, and headers in a concise manner.

  • express-validator:

    Select express-validator if you prefer a more declarative approach to validation that allows you to define validation rules directly in your route handlers. It is lightweight and easy to use, making it suitable for simple applications or when you need quick validations without additional dependencies.

  • joi:

    Opt for Joi if you need a powerful and flexible schema description language for JavaScript objects. Joi is particularly useful for complex validation scenarios, as it allows you to create detailed validation rules and provides extensive customization options.

  • yup:

    Consider Yup if you are looking for a validation library that works well with React and other front-end frameworks. Yup is built on the promise-based validation approach and is particularly effective for asynchronous validations, making it ideal for form handling in modern web applications.

README for celebrate

celebrate

Current Version Build Status airbnb-style Code Coverage Total Downloads

celebrate is an express middleware function that wraps the joi validation library. This allows you to use this middleware in any single route, or globally, and ensure that all of your inputs are correct before any handler function. The middleware allows you to validate req.params, req.headers, and req.query.

The middleware will also validate:

celebrate lists joi as a formal dependency. This means that celebrate will always use a predictable, known version of joi during the validation and compilation steps. There are two reasons for this:

  1. To ensure that celebrate can always use the latest version of joi as soon as it's published
  2. So that celebrate can export the version of joi it uses to the consumer to maximize compatibility

express Compatibility

celebrate is tested and has full compatibility with express 4 and 5. It likely works correctly with express 3, but including it in the test matrix was more trouble than it's worth. This is primarily because express 3 exposes route parameters as an array rather than an object.

Example Usage

Example of using celebrate on a single POST route to validate req.body.

const express = require('express');
const BodyParser = require('body-parser');
const { celebrate, Joi, errors, Segments } = require('celebrate');

const app = express();
app.use(BodyParser.json());

app.post('/signup', celebrate({
  [Segments.BODY]: Joi.object().keys({
    name: Joi.string().required(),
    age: Joi.number().integer(),
    role: Joi.string().default('admin')
  }),
  [Segments.QUERY]: {
    token: Joi.string().token().required()
  }
}), (req, res) => {
  // At this point, req.body has been validated and 
  // req.body.role is equal to req.body.role if provided in the POST or set to 'admin' by joi
});
app.use(errors());

Example of using celebrate to validate all incoming requests to ensure the token header is present and matches the supplied regular expression.

const express = require('express');
const { celebrate, Joi, errors, Segments } = require('celebrate');
const app = express();

// validate all incoming request headers for the token header
// if missing or not the correct format, respond with an error
app.use(celebrate({
  [Segments.HEADERS]: Joi.object({
    token: Joi.string().required().regex(/abc\d{3}/)
  }).unknown()
}));
app.get('/', (req, res) => { res.send('hello world'); });
app.get('/foo', (req, res) => { res.send('a foo request'); });
app.use(errors());

API

celebrate does not have a default export. The following methods encompass the public API.

celebrate(schema, [joiOptions], [opts])

Returns a function with the middleware signature ((req, res, next)).

  • requestRules - an object where key can be one of the values from Segments and the value is a joi validation schema. Only the keys specified will be validated against the incoming request object. If you omit a key, that part of the req object will not be validated. A schema must contain at least one valid key.
  • [joiOpts] - optional object containing joi options that are passed directly into the validate function. Defaults to { warnings: true }.
  • [opts] - an optional object with the following keys. Defaults to {}.
    • reqContext - bool value that instructs joi to use the incoming req object as the context value during joi validation. If set, this will trump the value of joiOptions.context. This is useful if you want to validate part of the request object against another part of the request object. See the tests for more details.
    • mode - optional Modes for controlling the validation mode celebrate uses. Defaults to partial.

celebrator([opts], [joiOptions], schema)

This is a curried version of celebrate. It is curried with lodash.curryRight so it can be called in all the various fashions that API supports. Returns a function with the middleware signature ((req, res, next)).

  • [opts] - an optional object with the following keys. Defaults to {}.
    • reqContext - bool value that instructs joi to use the incoming req object as the context value during joi validation. If set, this will trump the value of joiOptions.context. This is useful if you want to validate part of the request object against another part of the request object. See the tests for more details.
    • mode - optional Modes for controlling the validation mode celebrate uses. Defaults to partial.
  • [joiOpts] - optional object containing joi options that are passed directly into the validate function. Defaults to { warnings: true }.
  • requestRules - an object where key can be one of the values from Segments and the value is a joi validation schema. Only the keys specified will be validated against the incoming request object. If you omit a key, that part of the req object will not be validated. A schema must contain at least one valid key.
Sample usage

This is an example use of curried celebrate in a real server.

  const express = require('express');
  const { celebrator, Joi, errors, Segments } = require('celebrate');
  const app = express();

  // now every instance of `celebrate` will use these same options so you only
  // need to do it once.
  const celebrate = celebrator({ reqContext: true }, { convert: true });

  // validate all incoming request headers for the token header
  // if missing or not the correct format, respond with an error
  app.use(celebrate({
    [Segments.HEADERS]: Joi.object({
      token: Joi.string().required().regex(/abc\d{3}/)
    }).unknown()
  }));
  app.get('/', celebrate({
    [Segments.HEADERS]: Joi.object({
      name: Joi.string().required()
    })
  }), (req, res) => { res.send('hello world'); });
  app.use(errors());

Here are some examples of other ways to call celebrator

  const opts = { reqContext: true };
  const joiOpts = { convert: true };
  const schema = {
    [Segments.HEADERS]: Joi.object({
      name: Joi.string().required()
    })
  };

  let c = celebrator(opts)(joiOpts)(schema);
  c = celebrator(opts, joiOpts)(schema);
  c = celebrator(opts)(joiOpts, schema);
  c = celebrator(opts, joiOpts, schema);

  // c would function the same in all of these cases.

errors([opts])

Returns a function with the error handler signature ((err, req, res, next)). This should be placed with any other error handling middleware to catch celebrate errors. If the incoming err object is an error originating from celebrate, errors() will respond a pre-build error object. Otherwise, it will call next(err) and will pass the error along and will need to be processed by another error handler.

  • [opts] - an optional object with the following keys
    • statusCode - number that will be used for the response status code in the event of an error. Must be greater than 399 and less than 600. It must also be a number available to the node HTTP module. Defaults to 400.
    • message - string that will be used for the message value sent out by the error handler. Defaults to 'Validation failed'

If the error response format does not suite your needs, you are encouraged to write your own and check isCelebrateError(err) to format celebrate errors to your liking.

Errors origintating from the celebrate() middleware are CelebrateError objects.

Joi

celebrate exports the version of joi it is using internally. For maximum compatibility, you should use this version when creating schemas used with celebrate.

Segments

An enum containing all the segments of req objects that celebrate can validate against.

{
  BODY: 'body',
  COOKIES: 'cookies',
  HEADERS: 'headers',
  PARAMS: 'params',
  QUERY: 'query',
  SIGNEDCOOKIES: 'signedCookies',
}

Modes

An enum containing all the available validation modes that celebrate can support.

  • PARTIAL - ends validation on the first failure. Does not apply joi transformations if any part of the request is invalid.
  • FULL - validates the entire request object and collects all the validation failures in the result. Does not apply joi transformations if any part of the request is invalid.
    • Note: In order for this to work, you will need to pass abortEarly: false to #joiOptions. Or to get the default behavior along with this, { abortEarly: false, warnings: true }

new CelebrateError([message], [opts])

Creates a new CelebrateError object. Extends the built in Error object.

  • message - optional string message. Defaults to 'Validation failed'.
  • [opts] - optional object with the following keys
    • celebrated - bool that, when true, adds Symbol('celebrated'): true to the result object. This indicates this error as originating from celebrate. You'd likely want to set this to true if you want the celebrate error handler to handle errors originating from the format function that you call in user-land code. Defaults to false.

CelebrateError has the following public properties:

  • details - a Map of all validation failures. The key is a Segments and the value is a joi validation error. Adding to details is done via details.set. The value must be a joi validation error or an exception will be thrown.
Sample usage
  const result = Joi.validate(req.params.id, Joi.string().valid('foo'), { abortEarly: false });
  const err = new CelebrateError(undefined, { celebrated: true });
  err.details.set(Segments.PARAMS, result.error);

isCelebrateError(err)

Returns true if the provided err object originated from the celebrate middleware, and false otherwise. Useful if you want to write your own error handler for celebrate errors.

  • err - an error object

Additional Details

Validation Order

celebrate validates request values in the following order:

  1. req.headers
  2. req.params
  3. req.query
  4. req.cookies (assuming cookie-parser is being used)
  5. req.signedCookies (assuming cookie-parser is being used)
  6. req.body (assuming body-parser is being used)

Mutation Warning

If you use any of joi's updating validation APIs (default, rename, etc.) celebrate will override the source value with the changes applied by joi (assuming the request is valid).

For example, if you validate req.query and have a default value in your joi schema, if the incoming req.query is missing a value for default, during validation celebrate will overwrite the original req.query with the result of joi.validate. This is done so that once req has been validated, you can be sure all the inputs are valid and ready to consume in your handler functions and you don't need to re-write all your handlers to look for the query values in res.locals.*.

Additional Info

According the the HTTP spec, GET requests should not include a body in the request payload. For that reason, celebrate does not validate the body on GET requests.

Issues

Before opening issues on this repo, make sure your joi schema is correct and working as you intended. The bulk of this code is just exposing the joi API as express middleware. All of the heavy lifting still happens inside joi. You can go here to verify your joi schema easily.