Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Joi Validation Regex or pattern

I want to joi use regex pattern which define in variable

I have a variable pattern which contains regex i.e

pattern = "/^[0-9+]{7}-[0-9+]{1}$/"

and this pattern send to Joi module and want to confirm

module.exports = {
    save: {
        body: {
          match: Joi.string().regex(pattern).required
        }
     }
 }

I know validation work if I use this

module.exports = {
        save: {
            body: {
              match: Joi.string().regex(/^[0-9+]{7}-[0-9+]{1}$/).required
            }
         }
     }

But in my case every time regex will different. So I can not use above regex pattern

like image 621
Imran Rafiq Avatar asked Mar 13 '19 07:03

Imran Rafiq


People also ask

What is Joi validation?

Hapi Joi is an object schema description language and validator for JavaScript objects. With Hapi Joi, we create blueprints or schemas for JavaScript objects (an object that stores information) to ensure validation of key information.

What does this regex do?

Short for regular expression, a regex is a string of text that lets you create patterns that help match, locate, and manage text. Perl is a great example of a programming language that utilizes regular expressions. However, its only one of the many places you can find regular expressions.


1 Answers

If you want to use pattern as variable, just pass it:

module.exports = (pattern) => ({
  save: {
    body: {
      match: Joi.string().regex(pattern).required
    }
  }
});

And use it like:

const pattern = "/^[0-9+]{7}-[0-9+]{1}$/";
validator(pattern)
like image 90
Victor P. Avatar answered Sep 24 '22 15:09

Victor P.