4

I'm trying to validate if a string contains certain substrings defined inside an array:

const subStringElems= ['ELEM1', 'ELEM2', 'ELEM3', 'ELEM4'];

This is the code for the data validator:

const JoiValidator = require('@hapi/joi');

const subStringElems= ['ELEM1', 'ELEM2', 'ELEM3', 'ELEM4'];
let valSchema = {};

valSchema.manageDataParams = Joi.object().keys({
    stringToBeValidated: Joi.string().required(),
(...)

});

Is there any way to check if "stringToBeValidated" contains all of these 4 elements other than using regex for this purpose?

Eunito
  • 416
  • 5
  • 22
  • Please check [Nodejs - Joi Check if string is in a given list](https://stackoverflow.com/questions/41408469/nodejs-joi-check-if-string-is-in-a-given-list) – Wiktor Stribiżew Apr 17 '20 at 11:44
  • the idea here is the oposite: "text text text ELEM1 text text text text text text ELEM2 text ELEM4 text text text text text text ELEM3 text text text" and see if it contains all of those elements but using joi – Eunito Apr 17 '20 at 13:03

1 Answers1

0

Whats wrong with regex?

valSchema.manageDataParams = Joi.object().keys({
    stringToBeValidated: Joi.string().required()
     .regex(/ELEM1/)
     .regex(/ELEM2/)
     .regex(/ELEM3/)
     .regex(/ELEM4/),
(...)

});

or the other option would be .custom that allows any kind of validation rule.

valSchema.manageDataParams = Joi.object().keys({
    stringToBeValidated: Joi.string().required()
   .custom(value => {
      if(!value.includes('ELEM1') || !value.includes('ELEM2') || !value.includes('ELEM3') || !value.includes('ELEM4'))
      throw new Error('Value must contain all substrings ELEM1, ELEM2, ELEM3 and ELEM4')
  })

(...)

});
  • 1
    As it’s currently written, your answer is unclear. Please [edit] to add additional details that will help others understand how this addresses the question asked. You can find more information on how to write good answers [in the help center](/help/how-to-answer). – Community Aug 14 '23 at 10:07