Node.js + Joi how to display a custom error messages?

后端 未结 12 1553
故里飘歌
故里飘歌 2020-12-01 00:56

It seems pretty straight forward to validate user\'s input in Node.js RESTapi with Joi.

But the problem is that my app is not written in English. That m

12条回答
  •  情歌与酒
    2020-12-01 01:33

    The best solution I found was :

    Create a Middleware for JOI validation

    Validator.js - You can create your custom error object

    const Joi = require('Joi');
    
    module.exports = schema => (req, res, next) => {
      const result = Joi.validate(req.body, schema);
      if (result.error) {
        return res.status(422).json({
          errorCause: result.error.name,
          missingParams: result.error.details[0].path,
          message: result.error.details[0].message
        });
      }
      next();
    };
    
    

    In the routes or controller pass this middleware function

    
    const joiValidator = require('../utils/validator'); // Wherever you have declare the validator or middlerware
    
       const  userSchema = joi.object().keys({
        email : joi.string().email().required(),
        password : joi.string().required()
      });
    
      routes.routes('/').get(joiValidator(userSchema), (req, res) => {
        res.status(200).send('Person Check');
      });
    
    

提交回复
热议问题