【发布时间】:2019-01-06 20:53:01
【问题描述】:
我正在尝试为密码字段制定一个验证规则,该规则应包含以下内容:
- 必须有数字
- 必须至少包含一个大写字母
- 必须至少包含一个小写字母
- 必须包含以下任何符号 [@$!]
- 应仅包含 8 到 20 个字符。
这是我使用的正则表达式模式:(?=.*[a-z])(?=.*[A-Z])(?=.*\d)(?=.*[$@$!#.])[A-Za-z\d$@$!%*?&.]{8,20}
这是 Joi 验证:
password: Joi.string()
.regex(
'/(?=.*[a-z])(?=.*[A-Z])(?=.*d)(?=.*[$@$!#.])[A-Za-zd$@$!%*?&.]{8,20}/'
)
.required()
.min(8)
.max(20)
错误堆栈跟踪:
{ AssertionError [ERR_ASSERTION]: pattern must be a RegExp
at internals.String.regex (E:\nodeprojects\voting-system\voting-server\node_modules\joi\lib\types\string\index.js:120:14)
at Object.<anonymous> (E:\nodeprojects\voting-system\voting-server\src\routes\user.js:16:6)
at Module._compile (module.js:649:30)
at Object.Module._extensions..js (module.js:660:10)
at Module.load (module.js:561:32)
at tryModuleLoad (module.js:501:12)
at Function.Module._load (module.js:493:3)
at Module.require (module.js:593:17)
at require (internal/module.js:11:18)
at files.map (E:\nodeprojects\voting-system\voting-server\node_modules\hapi-auto-route\lib\auto-route.js:21:27)
at Array.map (<anonymous>)
at Object.module.exports.getRoutes (E:\nodeprojects\voting-system\voting-server\node_modules\hapi-auto-route\lib\auto-route.js:19:18)
at Object.register (E:\nodeprojects\voting-system\voting-server\node_modules\hapi-auto-route\index.js:16:32)
at <anonymous>
generatedMessage: false,
name: 'AssertionError [ERR_ASSERTION]',
code: 'ERR_ASSERTION',
actual: false,
expected: true,
operator: '==' }
【问题讨论】:
-
将
'(?=.*[a-z])(?=.*[A-Z])(?=.*\d)(?=.*[$@$!#.])[A-Za-z\d$@$!%*?&.]{8,20}'替换为/(?=.*[a-z])(?=.*[A-Z])(?=.*\d)(?=.*[$@$!#.])[A-Za-z\d$@$!%*?&.]{8,20}/。您的字符串未转义 ``. -
@Seblor 正则表达式已更新,但仍返回“AssertionError [ERR_ASSERTION]: pattern must be a RegExp”
-
你仍然在表达式周围使用引号,该函数需要一个 RegExp 对象,使用
.regex(/(?=.*[a-z])(?=.*[A-Z])(?=.*d)(?=.*[$@$!#.])[A-Za-zd$@$!%*?&.]{8,20}/) -
谢谢它的工作。