joi.array.delimiter()

Created on 26 Feb 2015  路  8Comments  路  Source: sideway/joi

Please add support for an array delimiter option to split a string input. This would be very convenient to support comma-delimited query parameters.

validate: {
   query: {
      sort: joi.array().items(joi.string()).single().delimiter(',').valid('givenName', 'displayName').default([])
   }
}
feature

Most helpful comment

This is an old issue, but I still needed that in order to make an API easier to use (?items=one,two,three) and came up with a solution that works if anyone needs it:

const Joi = require('joi')
const customJoi = Joi.extend((joi) => ({
  base: joi.array(),
  name: 'stringArray',
  coerce: (value, state, options) => (value.split ? value.split(',') : value)
}))

const scheme = customJoi.stringArray().items(Joi.string()).single()

All 8 comments

Same as #514, not going to happen. Pass an array in your querystring, hapi understands that perfectly fine.

This is an old issue, but I still needed that in order to make an API easier to use (?items=one,two,three) and came up with a solution that works if anyone needs it:

const Joi = require('joi')
const customJoi = Joi.extend((joi) => ({
  base: joi.array(),
  name: 'stringArray',
  coerce: (value, state, options) => (value.split ? value.split(',') : value)
}))

const scheme = customJoi.stringArray().items(Joi.string()).single()

That's indeed the best way to insert a custom parser in the validation flow, thanks for providing that example.

@berzniz What you think about this solution?

Joi.extend((joi) => ({
    base: joi.array(),
    name: 'stringArray',
    coerce: (value, state, options) => {
      if(typeof value !== 'string') {
        return value;
      }

      return value.replace(/^,+|,+$/mg, '').split(',');
    },
  }));

The comma at the end of the string results in an additional empty item which I don't think is quite useful in this case.

This is precisely why I didn't want to deal with that, we could have endless discussions about each and every quirks your personal custom formats could have 馃槄 That's the problem with non-standard things.

I agree with @Marsup -- I just shared the solution I found since it took me some time to figure out 1 - that it is possible and 2 - how to do it

@Marsup @berzniz I agree, just wanted to share my notes and modifications about your solution. No need to continue the discussion about this :smile:

This thread has been automatically locked due to inactivity. Please open a new issue for related bugs or questions following the new issue template instructions.

Was this page helpful?
0 / 5 - 0 ratings

Related issues

REBELinBLUE picture REBELinBLUE  路  3Comments

sergibondarenko picture sergibondarenko  路  3Comments

kevbook picture kevbook  路  4Comments

PaunPrashant picture PaunPrashant  路  3Comments

longweiquan picture longweiquan  路  3Comments