Search code examples
javascriptnode.jsvalidationexpressjoi

Joi.js form validation - returning messages as json


I'm using express-validation and Joi packages for validating forms on serverside and whenever an error occurs it returns and html page as a response, is it possible to just return a json object?

Route file:

// Validator configuration
const validate = require('express-validation');
const validation = require('../validation/index');
.
.
.
router.post('/login', validate(validation.login), (req, res) => {
// Rest of code

Login validation file:

const joi = require('joi');

module.exports = {
    body: {
        emailOrUsername: joi.string().required(),
        password: joi.string().required()
    }
};

and it returns this:

<!DOCTYPE html>
<html lang="en">
    <head>
        <meta charset="utf-8">
        <title>Error</title>
    </head>
    <body>
 <pre>{&quot;status&quot;:400,&quot;statusText&quot;:&quot;Bad Request&quot;,&quot;errors&quot;:[{&quot;field&quot;:[&quot;emailOrUsername&quot;],&quot;location&quot;:&quot;body&quot;,&quot;messages&quot;:[&quot;\&quot;emailOrUsername\&quot; is not allowed to be empty&quot;],&quot;types&quot;:[&quot;any.empty&quot;]},{&quot;field&quot;:[&quot;password&quot;],&quot;location&quot;:&quot;body&quot;,&quot;messages&quot;:[&quot;\&quot;password\&quot; is not allowed to be empty&quot;],&quot;types&quot;:[&quot;any.empty&quot;]}]}</pre>
    </body>
</html>

Solution

  • Yes, it is possible - just use simple middleware:

    app.use((err, req, res, next) => {
      return res.status(err.status).json(err)
    });
    

    Check doc - it says:

    error handler is required as of 0.3.0, example:

    // error handler, required as of 0.3.0
    app.use(function(err, req, res, next){
      res.status(400).json(err);
    });