简体   繁体   中英

Joi custom error for each validation option

I have Joi schema and want to specify a custom error message for each of the options.

Example of my schema:

const schema = Joi.object().keys({
    name: Joi.string()
      .min(5).error(() => 'first message')
      .max(25).error(() => 'second message')
      .required().error(() => 'third message')
)}

At the moment this validation works in such way: if whatever of the option is invalid only third message appears.

Expected behavior - error message appears according to which option is invalid (as default Joi behavior, but with my custom error message).

Thanks in regards!

const schema = Joi.object().keys({
title: Joi.string()
  .min(5)
  .max(25)
  .required()
  .messages({
  "string.min": "first msg",
  "string.max": "second msg",
  "any.empty":"third msg"
      })
  })

These is the best way to show custom error messages

For my situation I just found such solution:

const schema = Joi.object().keys({
    title: Joi.string()
      .min(5)
      .max(25)
      .required()
      .error((errors) => {
        return errors.map(error => {
          switch (error.type) {
            case "string.min":
              return { message: "first msg" };
            case "string.max":
              return { message: "second msg" };
            case "any.empty":
              return { message: "third msg" };
          }
        }
        )
      })

Seems not the best one, as it cause too many code, especialy if you have big form, hovewer it works as I desire.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM