Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

joi

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?

like image 447
juztcode Avatar asked Oct 20 '25 14:10

juztcode


1 Answers

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.

like image 72
soltex Avatar answered Oct 23 '25 08:10

soltex



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!