javascriptnode.jsjoi

Disallow multiple regex patterns in a Joi schema property


I want to add a Joi schema property that disallows multiple regex patterns.
I've tried the following but it didn't work:

const schema = Joi.object({
  a: Joi.string().invalid(
    Joi.string().pattern(/^\d+$/),
    Joi.string().pattern(/^Hello \d+$/),
  )
});

I also tried using the alternatives method:

const schema = Joi.object({
  a: Joi.alternatives().try(
    Joi.string().pattern(/^\d+$/),
    Joi.string().pattern(/^Hello \d+$/),
  ).not().match('all')
});

Here, I get the following error: Cannot merge type string with another type: alternatives

Any ideas?


Solution

  • Try using invert option in string.pattern()

    Working Demo

    const schema = Joi.object({
      a: Joi.string()
        .pattern(/^\d+$/, { invert: true })
        .pattern(/^Hello \d+$/, { invert: true }),
    });