Node.js + Joi how to display a custom error messag

2020-02-17 09:10发布

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!

标签: node.js joi
9条回答
闹够了就滚
2楼-- · 2020-02-17 10:06

Solution to add custom messages: Simply add another chained function to throw error while defining your schema.
In your case

 firstName: Joi.string().min(5).max(10).required().error(new Error('I am a custom error and I know it!')),

Rest will remain same.

Solution to use Joi at client side (Your 2nd question)

Joi-Browser is the package which enables usage of the same schema at the client side.

Here is an interesting discussion you can have a look at.

Cheers!

查看更多
▲ chillily
3楼-- · 2020-02-17 10:07

You can use .error(new Error('message')), And its work for me

var schema = Joi.object().keys({
  firstName: Joi.string().min(5).max(10).required().error(new Error('Give your error message here for first name')),
  lastName: Joi.string().min(5).max(10).required().error(new Error('Give your error message here for last name'))
  ..
});

Joi.validate(req.body, schema, function(err, value) {
  if (err) {
    console.log(err.message)
    return catched(err.message); 
  }
});
查看更多
戒情不戒烟
4楼-- · 2020-02-17 10:11

let schema = Joi.object({ foo: Joi.number().min(0).error(() => '"foo" requires a positive number') });

Docs link

查看更多
登录 后发表回答