Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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!

like image 927
Orest Bats Avatar asked Apr 26 '26 12:04

Orest Bats


2 Answers

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

like image 131
SurendraSawant Avatar answered Apr 28 '26 02:04

SurendraSawant


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.

like image 27
Orest Bats Avatar answered Apr 28 '26 03:04

Orest Bats



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!