Joi Validation Regex or pattern

|▌冷眼眸甩不掉的悲伤 提交于 2021-02-16 20:23:49

问题


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


回答1:


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)



回答2:


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


来源:https://stackoverflow.com/questions/55136627/joi-validation-regex-or-pattern

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!