Jojo
Jojo

Reputation: 490

Hapi/Joi validation - different Joi.regex depending on another key value

I have a scenario where I need to validate a vat number with different regex depending on which country it is. So when the field language is SE i want to use this regex /^\d{6}-\d{4}$/ on the field company.vatNo, but when the field language is NO i want to use this one /^\d{9}(MVA)?$/.. I thought i could go with Joi's when(), but it doesnt seem to work at all. Does anybody know how i can achieve this?

Here's my route where i validate:

module.exports = {
  method: 'POST',
  path: '/signup/{partner}',
  handler: createPartner,
  config: {
    validate: {
      payload: {
        language: Joi.string().allow(config.supportedLanguages).required(),
        company: {
         vatNo: {

           Joi
           .when('language', {
             is: 'SE', 
             then: Joi.string().regex(/^\d{6}-\d{4}$/).required()
           })
           .when('language', {
             is: 'NO',
             then: Joi.string().regex(/^\d{9}(MVA)?$/).required()
           })
           .when('language', {
             is: 'FI',
             then: Joi.string().regex(/^\d{7}-\d{1}$/).required()
           })

        }
      }
    }
  }
}

Thanks

Upvotes: 0

Views: 1117

Answers (1)

Jojo
Jojo

Reputation: 490

Here's the solution. It seems like Joi doesn't recognize language if vatNo is inside another object. But this solved the problem:

    language: Joi.any().valid(config.supportedLanguages).required(),
    vatNo:
      Joi.alternatives()
        .when('language', {
          is: Joi.string().regex(/^(SE)$/i),
          then: Joi.string().regex(/^\d{6}-\d{4}$/).label('companyID')
        })
        .when('language', {
          is: Joi.string().regex(/^(NO)$/i),
          then: Joi.string().regex(/^\d{9}(MVA)?$/).label('companyID')
        })
        .when('language', {
          is: Joi.string().regex(/^(FI)$/i),
          then: Joi.string().regex(/^\d{7}-\d{1}$/).label('companyID')
        }),

Upvotes: 2

Related Questions