4

How to make a custom message using joi? i saw many answered question related on this but i dont know why it didnt work on my end, the error message always appeared is "Student" does not contain 1 required value(s) what i want is "Student" This field is required.

export const VALIDATION_SCHEMA = {
  students: Joi.array()
    .label('Student Name(s)')
    .items(
      Joi.object({
        name: Joi.string(),
        value: Joi.string()
      }).required().messages('"Student" This field is required.')
    ),
}

2 Answers2

0

You can return a custom error object using Error constructor like this:

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

 Joi.validate(req.body, schema, function(err, value) {
    if (err) {
        console.log(err.message)
        return catched(err.message); 
        }
   });
Bhaskar
  • 302
  • 2
  • 13
0

The easiest way in my opinion would be this.

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

export const categorySchema = Joi.object({
    mobile: Joi.string().trim().regex(/^[6-9]\d{9}$/).required().messages({
        "string.base": `"" should be a type of string`,
        "string.empty": `"" must contain value`,
        "string.pattern.base": `"" must be 10 digit number`,
        "any.required": `"" is a required field`
    }),
    password: Joi.string().trim().required().messages({
        "string.base": `"" should be a type of 'text'`,
        "string.pattern.base": `"" must be 10 digit number`,
        "any.required": `"" is a required field`
    }),
}).required();