简体   繁体   English

Joi 验证正则表达式或模式

[英]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并将此模式发送到 Joi 模块并要确认

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()
       }
   }
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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