我正在尝试使用 Express-validator 定义一个架构,在其中设置“isStrongPassword”选项。 “usernameSchema”工作正常,但“passwordSchema”不会传递我输入的密码,即使它们符合要求。
这是我的代码:
用户路由器.js
const { usernameSchema, passwordSchema } = require("../services/validationSchemas");
router.post("/register", checkSchema({ username: usernameSchema, password: passwordSchema }), (req, res) => {
const result = validationResult(req);
if (result.isEmpty()) {
res.json({
username: req.query.username,
password: req.query.password
});
} else {
res.send({
errors: result.array()
});
}
});
validationSchemas.js
const usernameSchema = {...};
const passwordSchema = {
errorMessage: "Enter a valid password.",
trim: true,
notEmpty: {
bail: true
},
isStrongPassword: {
minLength: 8,
minLowercase: 1,
minUppercase: 1,
minNumbers: 1
},
errorMessage: "Password doesn't match the requirements."
};
module.exports = {
usernameSchema: usernameSchema,
passwordSchema: passwordSchema
};
即使我输入符合要求的密码,我也会收到以下错误:
{
"errors": [
{
"type": "field",
"value": "124sdjAfsd",
"msg": "Password doesn't match the requirements.",
"path": "password",
"location": "query"
}
]
}
有人可以帮我解决这个问题吗?
最佳答案
现在做了一些测试(版本7.0.1)
Express 验证器使用默认值,除非您覆盖它们,否则您不会通过,因为您没有覆盖 minSymbols,因此它需要 1 个特殊字符。
但是如果您使用架构,则会出现一个错误,您根本无法覆盖默认值(8 个字符、1 个小数、1 个大数、1 个数字和 1 个特殊值),
即使使用这个疯狂的配置,我也可以使用这个密码:aA1@1245
:
const passwordSchema = {
trim: true,
notEmpty: {
bail: true
},
isStrongPassword: {
minLength: 1000000000,
minLowercase: 1000000000,
minUppercase: 1000000000,
minNumbers: 1000000000,
minSymbols: 1000000000
},
errorMessage: "Gotta be kidding"
};
为了能够实现您想要的(覆盖 minSymbol),您必须使用链验证:
const passwordConfig = {
minLength: 8,
minLowercase: 1,
minUppercase: 1,
minNumbers: 1,
minSymbols: 0 //🟥 dont require special chars
}
router.post("/register",
checkSchema({ username: usernameSchema }), //🟥 first middleware - schema validation
query('password').isStrongPassword(passwordConfig), //🟥 second middleware - chain validation
(req, res) => {
const result = validationResult(req);
if (result.isEmpty()) {
res.json({
username: req.query.username,
password: req.query.password
});
} else {
res.send({
errors: result.array()
});
}
});
关于javascript - 在验证模式中使用 isStrongPassword,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/76485486/