【问题标题】:Error: pattern must be a RegExp错误:模式必须是正则表达式
【发布时间】:2014-12-13 13:32:58
【问题描述】:

我需要接受手机号码作为网络服务的输入,但在使用 Joi 框架进行验证时遇到以下问题。

乔伊说:

Error: pattern must be a RegExp
    at Object.exports.assert (/home/gaurav/Gaurav-Drive/code/nodejsWorkspace/ragchews/node_modules/joi/node_modules/hoek/lib/index.js:524:11)
    at internals.String.regex (/home/gaurav/Gaurav-Drive/code/nodejsWorkspace/ragchews/node_modules/joi/lib/string.js:107:10)
    at /home/gaurav/Gaurav-Drive/code/nodejsWorkspace/ragchews/src/validators/userValidator.js:10:40
    at Object.<anonymous> (/home/gaurav/Gaurav-Drive/code/nodejsWorkspace/ragchews/src/validators/userValidator.js:13:2)
    at Module._compile (module.js:456:26)
    at Object.Module._extensions..js (module.js:474:10)
    at Module.load (module.js:356:32)
    at Function.Module._load (module.js:312:12)
    at Module.require (module.js:364:17)

用于验证:

var userProfileValidation = function(){
    return {
        payload : {
            uid: Joi.string().required().alphanum().length(userConfigs.UID_LENGTH),
            mobile_num: Joi.string().required().regex('^[0-9]*$').length(userConfigs.RMN_LENGTH) //for this guy
        }
    };
}();

我检查了freeformatter 上的正则表达式,它似乎至少对某些输入工作正常。我不明白为什么 joi 会抛出这个错误。

【问题讨论】:

  • 也许你需要在模式的末尾添加//^[0-9]*$/

标签: regex node.js hapijs joi


【解决方案1】:

实际上,正如 here (link) 所记录的那样,Joi 框架 在这里期望的不是 regex 模式,而是 实际的 regex。即:你应该使用:

Joi.string().required().regex(/^[0-9]*$/) [...]

...而不是:

Joi.string().required().regex('^[0-9]*$') [...]

【讨论】:

    猜你喜欢
    • 2019-09-17
    • 2019-12-24
    • 2012-03-31
    • 1970-01-01
    • 2018-11-23
    • 1970-01-01
    • 2022-08-06
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多