Sign Up

Have an account? Sign In Now

Sign In

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

Sorry, you do not have a permission to ask a question, You must login to ask question.

Forgot Password?

Need An Account, Sign Up Here
Sign InSign Up

ErrorCorner

ErrorCorner Logo ErrorCorner Logo

ErrorCorner Navigation

  • Home
  • Contact Us
  • About Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Contact Us
  • About Us
Home/ Questions/Q 927
Answered
Kenil Vasani
Kenil Vasani

Kenil Vasani

  • 646 Questions
  • 567 Answers
  • 77 Best Answers
  • 26 Points
View Profile
  • 4
Kenil Vasani
Asked: December 19, 20202020-12-19T22:01:13+00:00 2020-12-19T22:01:13+00:00

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

  • 4

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!

joinode.js
  • 1 1 Answer
  • 9 Views
  • 0 Followers
  • 0
Answer
Share
  • Facebook

    1 Answer

    • Voted
    1. Kenil Vasani

      Kenil Vasani

      • 646 Questions
      • 567 Answers
      • 77 Best Answers
      • 26 Points
      View Profile
      Best Answer
      Kenil Vasani
      2020-12-19T21:55:51+00:00Added an answer on December 19, 2020 at 9:55 pm

      Edit:

      Make sure you are using @hapi/joi – https://www.npmjs.com/package/@hapi/joi, version 16 and above.


      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.

      • 6
      • Share
        Share
        • Share on Facebook
        • Share on Twitter
        • Share on LinkedIn
        • Share on WhatsApp

    You must login to add an answer.

    Forgot Password?

    Sidebar

    Ask A Question
    • Popular
    • Kenil Vasani

      SyntaxError: invalid syntax to repo init in the AOSP code

      • 5 Answers
    • Kenil Vasani

      xlrd.biffh.XLRDError: Excel xlsx file; not supported

      • 3 Answers
    • Kenil Vasani

      Homebrew fails on MacOS Big Sur

      • 3 Answers
    • Kenil Vasani

      runtimeError: package fails to pass a sanity check for numpy ...

      • 3 Answers
    • Kenil Vasani

      Python, Error while installing matplotlib

      • 2 Answers

    Explore

    • Most Answered
    • Most Visited
    • Most Voted
    • Random

    © 2020-2021 ErrorCorner. All Rights Reserved
    by ErrorCorner.com