Skip to content

Trying to get multiple custom error messages in details array with {abortEarly: false} #1568

@samskeller

Description

@samskeller

Hi there -- I'm relatively new to Joi, so I certainly may be missing something, but I'm having trouble surfacing multiple custom error messages. I'm using version 13.4.0. I've tried two different methods but neither seem to produce what I'm looking for -- putting multiple custom error messages into the .error.details array of objects on the returned error message when using {abortEarly: false}.

For example, doing this:

const schema = Joi.object().keys({
  a: Joi.string().error(() => 'first error'),
  b: Joi.number().error(() => 'second error')
})
Joi.validate({a: 1, b: false}, schema, {abortEarly: false})

produces an object where the .error.message has the custom errors, but the .error.details array has the default error messages:

{ 
  error: { 
    ValidationError: child "a" fails because [first error]. child "b" fails because [second error]
    ...
    details: [{
      message: '"a" must be a string',
      path: [ 'a' ],
      type: 'string.base',
      context: { value: 1, key: 'a', label: 'a' }
    }, {
      message: '"b" must be a number',
      path: [ 'b' ],
      type: 'number.base',
      context: { key: 'b', label: 'b' }
    }]
  }
 ...
}

However, if I pass a new Error() in the .error() function, I only get a single error returned even though I'm explicitly saying {abortEarly: false}:

const schema = Joi.object().keys({
  a: Joi.string().error(new Error('first error')),
  b: Joi.string().error(new Error('second error'))
})
Joi.validate({a: 1, b: false}, schema, {abortEarly: false})

produces:

{ error: 
   Error: first error
       at repl:2:23
       at ContextifyScript.Script.runInThisContext (vm.js:44:33)
       at REPLServer.defaultEval (repl.js:239:29)
       at bound (domain.js:301:14)
       at REPLServer.runBound [as eval] (domain.js:314:12)
       at REPLServer.onLine (repl.js:440:10)
       at emitOne (events.js:120:20)
       at REPLServer.emit (events.js:210:7)
       at REPLServer.Interface._onLine (readline.js:279:10)
       at REPLServer.Interface._line (readline.js:626:8),
  value: { a: 1, b: false },
  then: [Function: then],
  catch: [Function: catch] }

Is there anyway to use custom error messages and get them to appear in the details array?

Thanks!

Metadata

Metadata

Assignees

Labels

breaking changesChange that can breaking existing codefeatureNew functionality or improvement

Type

No type

Projects

No projects

Milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions