簡體   English   中英

Joi 驗證正則表達式或模式

[英]Joi Validation Regex or pattern

我想使用在變量中定義的正則表達式模式

我有一個包含正則表達式的變量模式,即

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

並將此模式發送到 Joi 模塊並要確認

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

如果我使用這個,我知道驗證工作

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

但就我而言,每次正則表達式都會有所不同。 所以我不能使用上面的正則表達式模式

如果要將模式用作變量,只需傳遞它:

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

並像這樣使用它:

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