Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

joi: Custom errors are not returned, abortEarly is set to false

I can't get this joi validation to return all the errors just like what it does with default errors.

So here I'm setting individual custom errors for each field:

const schema = Joi.object().keys({
    a: Joi.string().error(new Error('must be string')), 
    b: Joi.number().error(new Error('must be number'))
});

Then when validating with abortEarly set to false, it only returns the first error it will encounter.

Joi.validate({a: 1, b: false}, schema, {abortEarly: false})

The error returned is like this,

{ error: [Error: must be string], value: { a: 1, b: false }}

when it should be returning all the errors in some manner.

Am I using abortEarly incorrectly or is there a process needed to be done in returning all custom errors? Thanks in advance for any response.

like image 345
Phenelo Avatar asked Sep 18 '25 18:09

Phenelo


1 Answers

Well, I think I found the answer. My joi library wasn't updated so I had it rolled up to 10.4.1 from 10.2.x. There was some features that I've seen in the documentation that didn't work when I tried it in the older version, including the solution I did.

I tried using this pattern and it works:

const schema = Joi.object().keys({
    a: Joi.string().error(() => 'must be string'), 
    b: Joi.number().error(() => 'must be number')
});

Like so:

{ [ValidationError: child "a" fails because [must be string]. child "b" fails because [must be number]]
  isJoi: true,
  name: 'ValidationError',
  details: 
   [ { message: '"a" must be a string',
       path: 'a',
       type: 'string.base',
       context: [Object] },
     { message: '"b" must be a number',
       path: 'b',
       type: 'number.base',
       context: [Object] } ],
  _object: { a: 1, b: false },
  annotate: [Function] }

Then I'll just parse the error.message to get all the error messages and process it.

'child "a" fails because [must be string]. child "b" fails because [must be number]'
like image 198
Phenelo Avatar answered Sep 21 '25 07:09

Phenelo