Search code examples
joi

joi.label , what does this method of joi schema validation do


I just came across this line of code that I had to work on:

Joi.array().label('Emails').items(Joi.string()).required()

I particularly didn't understand what .label('Emails') was doing, so, I hit the documentation:

Overrides the key name in error messages.

name - the name of the key.

const schema = { first_name: Joi.string().label('First Name') };

and this particularly didn't make any sense to me. Because, is First Name, Emails particular parameters that can be passed? What is it overriding? What other arguments can we pass, etc. What is this method doing particularly?


Solution

  • If you have this schema:

    const schema = Joi.object({
      first_name: Joi.string().label('First Name')
    });
    

    and you validate an invalid object (passing first_name as number type):

    const { error, value } = schema.validate({ first_name: 123 })
    

    This is how the error.details object will look like:

    [
      {
        message: 'first_name must be a string',
        path: [ 'first_name' ],
        type: 'string.base',
        context: {
          label: 'First Name',
          valids: 123,
          key: 'first_name'
        }
      }
    ]
    

    However, if you use .label('First Name') this is what you get from the error object:

    [
      {
        message: 'First Name must be a string', <-- OVERRIDES
        path: [ 'first_name' ],
        type: 'string.base',
        context: {
          label: 'First Name', <-- OVERRIDES
          valids: 123,
          key: 'first_name'
        }
      }
    ]
    

    So, .label will override the message and the context.label.

    According to the documentation you can't pass any other argument.