Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
620 views
in Technique[技术] by (71.8m points)

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

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 means I need to send a custom written messages to the frontend user.

I have googled for this and only found issues.

Maybe could someone give a solution for this?

This is the code I am using to validate with the Joi system:

    var schema = Joi.object().keys({
      firstName: Joi.string().min(5).max(10).required(),
      lastName: Joi.string().min(5).max(10).required()
      ..
    });

    Joi.validate(req.body, schema, function(err, value) {
      if (err) {
        return catched(err.details); 
      }
    });

    function catched(reject) {
      res.json({
        validData: false,
        errors: reject
      });
    }

Plus, is there a way to use Joi in client side?

Thanks!

question from:https://stackoverflow.com/questions/48720942/node-js-joi-how-to-display-a-custom-error-messages

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Original answer:

The current way (I personally find it better) is to use .messages() (or .prefs({messages})).

const Joi = require('@hapi/joi');

const joiSchema = Joi.object({
  a: Joi.string()
    .min(2)
    .max(10)
    .required()
    .messages({
      'string.base': `"a" should be a type of 'text'`,
      'string.empty': `"a" cannot be an empty field`,
      'string.min': `"a" should have a minimum length of {#limit}`,
      'any.required': `"a" is a required field`
    })
});

const validationResult = joiSchema.validate({ a: 2 }, { abortEarly: false });
console.log(validationResult.error); // expecting ValidationError: "a" should be a type of 'text'

Usage of .errors() is not recommended just to update default message with custom message.

.prefs({ messages }) is an elaborate way to provide more options as preferences. The other options for prefs are taken directly from options of .validate()

Further read: https://github.com/hapijs/joi/issues/2158


Update 1: I saw that the above explanation did not work out for some folks, so I have put up some code to test yourself. Check it here: https://runkit.com/embed/fnfaq3j0z9l2

Also updated the code snippet shared previously to have details from package inclusion, to usage, to calling the actual validation method.


Update 2: The list of joi error types and their description (for .messages() - like string.base, array.unique, date.min etc..) is available here.


Update 3: Joi has moved from hapi project to standalone: https://www.npmjs.com/package/joi. Make sure you are using latest version (or at least above v17).


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...