简体   繁体   中英

Complex validation using Joi library

I have this json:

let purchaseSubscription = {
  'metadata': {
    'eventName': 'PurchaseSubscription',
    'type': 'setup' // setup, repurchase or recurring
  },
  'data': {
    'subscriptionId': '447481',
    'subscriptionTrialId': '23542'
  }
};

If the metadata.type has value setup then data.subscriptionTrialId should be validated for existence and to be a number. If the metadata.type has other values, the data.subscriptionTrialId can be ignored.

This is what I currently have:

const Joi = require('joi');
const validTypes = ['setup', 'repurchase', 'recurring'];

exports.schema = Joi.object().keys({
  metadata: Joi.object({
    eventName: Joi.string().required(),
    type: Joi.string().valid(validTypes).required()
  }).required(),
  data: Joi.object({
    subscriptionId: Joi.number().integer().min(1).max(2147483647).required(),
    subscriptionTrialId: Joi.when(
        'metadata.type', { is: 'setup', then: Joi.required() })
  }).required()
}).options({ 'allowUnknown': true });

But I am not getting desired results. The data.subscriptionTrialId is always validated, no matter what I have under metadata.type

I tried reading documentation , but can't make it to work :(

You can use the otherwise key in the JOI schema.

Somewhere in your code before declaring exports.schema :

const trialIdRequired = Joi.object({
    subscriptionId: Joi.number().integer().min(1).max(2147483647).required(),
    subscriptionTrialId: Joi.required()
  }).required()

const trialIdNotRequired = Joi.object({
   subscriptionId: Joi.number().integer().min(1).max(2147483647).required(),
    subscriptionTrialId: Joi.any()
})

And then add a when clause to the data field

data: Joi.when(
        'metadata.type', 
        { 
            is: 'setup', 
            then: trialIdRequired,
            otherwise: trialIdNotRequired
        })

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM