Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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()
});
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading