Search code examples
node.jsvalidationjoi

How to validate string fields using constant values from object?


I want to take this code and enhance it to have the String values saved as constants

const toValidate = Joi.object({
    emailTiming: Joi.string().valid('DAILY','WEEKLY','MONTHLY','QUARTERLY','MEDIAN','YEARLY').required()
});

So I created this object:

  EMAIL_DISPATCH_TIMING: {
    DAILY: 'DAILY', 
    WEEKLY: 'WEEKLY', 
    MONTHLY: 'MONTHLY', 
    QUARTERLY: 'QUARTERLY', 
    MEDIAN: 'MEDIAN', 
    YEARLY: 'YEARLY'
  }

I wanted to know how can I get the values from this object and set them as valid values to my field.

Currently I tried this, and it didn't work -

emailTiming: Joi.string().valid(Object.values(EMAIL_DISPATCH_TIMING)).required(),

Solution

  • valid accepts a rest parameter, therefore you need to use the spread operator:

    const items = {
      DAILY: 'DAILY',
      WEEKLY: 'WEEKLY',
      MONTHLY: 'MONTHLY',
      QUARTERLY: 'QUARTERLY',
      MEDIAN: 'MEDIAN',
      YEARLY: 'YEARLY'
    };
    
    const toValidate = Joi.object({
      emailTiming: Joi.string().valid(...Object.values(items)).required()
    });