简体   繁体   中英

Joi Validation Regex or pattern

I want to joi use regex pattern which define in variable

I have a variable pattern which contains regex ie

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

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)
module.exports = (exp) => ({
   save: {
       body: {
         match: Joi.string().pattern(new RegExp(exp)).required()
       }
   }
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM