我试图为密码字段制定一个验证规则,它应该由以下内容组成:
下面是我使用的regex模式:(?=.*[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: '==' }发布于 2020-04-29 14:39:54
我知道已经过去两年了,但我认为迟到总比不来好。
您只需将模式放入RegExp()中即可。
这就是我如何编辑您的代码:)
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)我希望它能帮到你!
发布于 2021-10-03 08:02:13
正则表达式不需要字符串中的任何单引号(开始/结束)
下面是一个运行良好的例子。
const joi = require("joi");
const strongPasswordRegex = /^(?=.*?[A-Z])(?=.*?[a-z])(?=.*?[0-9])(?=.*?[#?!@$%^&*-]).{8,}$/;
const stringPassswordError = new Error("Password must be strong. At least one upper case alphabet. At least one lower case alphabet. At least one digit. At least one special character. Minimum eight in length")
const schema = joi.object().keys({
username: joi.string().required().min(4).max(15),
password: joi.string().regex(strongPasswordRegex).error(stringPassswordError).required()
});
const notValid = schema.validate({ username: "MHamzaRajput", password: "Admin@admin123" }).error;
if (notValid) {
console.log(notValid.message);
} else {
console.log("payload validated successfully");
}https://stackoverflow.com/questions/51596779
复制相似问题