问题
I'm trying to make a validation rule for password field that it should consists of the following:
- Must have a number
- Must contain at least one upper-case
- Must contain at least one lower-case
- Must contain any of the following symbols [@$!]
- Should be at 8 to 20 characters only.
Here's the regex pattern I use: (?=.*[a-z])(?=.*[A-Z])(?=.*\d)(?=.*[$@$!#.])[A-Za-z\d$@$!%*?&.]{8,20}
Tested on https://regexr.com/
Here's the Joi validation:
password: Joi.string()
.regex(
'/(?=.*[a-z])(?=.*[A-Z])(?=.*d)(?=.*[$@$!#.])[A-Za-zd$@$!%*?&.]{8,20}/'
)
.required()
.min(8)
.max(20)
The error stacktrace:
{ 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: '==' }
回答1:
I know it has been about 2 years but I think coming late is better than never coming 🤣🤣.
You just have to put the pattern inside a RegExp()
This is how I edited your code :)
const pattern = "/(?=.*[a-z])(?=.*[A-Z])(?=.*d)(?=.*[$@$!#.])[A-Za-zd$@$!%*?&.]{8,20}/";
password: Joi.string()
.regex(RegExp(pattern)) // you have to put it in this way and it will work :)
.required()
.min(8)
.max(20)
I hope it helps you!
来源:https://stackoverflow.com/questions/51596779/joi-regex-is-not-recognized-as-regex-pattern