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

后端 未结 12 1515
故里飘歌
故里飘歌 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:15

    For anyone having a problem with

    ...messages is not a function

    errors, you must install joi with npm install @hapi/joi, and importing it with @hapi/joi. I've made the mistake of installing joi without the @hapi/ prefix and it took me a while to find the error.

    0 讨论(0)
  • 2020-12-01 01:19

    In the latest version use message as.

    var schema = Joi.object().keys({
      firstName: Joi.string().min(5).max(10).required().messages({
        "string.base": `"username" should be a type of 'text'`,
        "string.empty": `"username" cannot be an empty field`,
        "any.required": `"username" is a required.`,
      }),
      lastName: Joi.string().min(5).max(10).required().messages({
        "string.base": `"lastName" should be a type of 'text'`,
        "string.empty": `"lastName" cannot be an empty field`,
        "any.required": `"lastName" is a required.`,
      }),
      [...]
    });
    
    0 讨论(0)
  • 2020-12-01 01:20

    Extending on Ashish Kadam's answer, if you have many different error types, you can check which type of error is present, and set its message accordingly:

    var schema = Joi.object().keys({
      firstName: Joi.string().min(5).max(10).required().error(errors => {
        errors.forEach(err => {
          switch (err.type) {
            case "any.empty":
              err.message = "Value should not be empty!";
              break;
            case "string.min":
              err.message = `Value should have at least ${err.context.limit} characters!`;
              break;
            case "string.max":
              err.message = `Value should have at most ${err.context.limit} characters!`;
              break;
            default:
              break;
          }
        });
        return errors;
      }),
      // ...
    });
    

    You can check the list of errors here: Joi 14.3.1 API Reference > Errors > List of errors

    Also you can check the any.error reference for more information. Quoting the docs:

    Overrides the default joi error with a custom error if the rule fails where:

    • err can be:
      • an instance of Error - the override error.
      • a function(errors), taking an array of errors as argument, where it must either:
        • return a string - substitutes the error message with this text
        • return a single object or an Array of it, where:
          • type - optional parameter providing the type of the error (eg. number.min).
          • message - optional parameter if template is provided, containing the text of the error.
          • template - optional parameter if message is provided, containing a template string, using the same format as usual joi language errors.
          • context - optional parameter, to provide context to your error if you are using the template.
        • return an Error - same as when you directly provide an Error, but you can customize the error message based on the errors.
    • options:
      • self - Boolean value indicating whether the error handler should be used for all errors or only for errors occurring on this property (true value). This concept only makes sense for array or object schemas as other values don't have children. Defaults to false.
    0 讨论(0)
  • 2020-12-01 01:21

    A solution I have found is to set:

    var schema = Joi.object().keys({
      firstName: Joi.string().min(5).max(10).required().label("Your error message in here"),
      lastName: Joi.string().min(5).max(10).required()
      ..
    });
    

    Then print the label from the callback error variable

    0 讨论(0)
  • 2020-12-01 01:21

    Just call "message()" function :

    firstName: Joi.string().message("Your custom message")
    
    0 讨论(0)
  • 2020-12-01 01:24
    let schema = Joi.object().keys({
       Joi.string().required().options({language: {any: {required: "First name is required"}}})
    });
    
    0 讨论(0)
提交回复
热议问题