I’m trying to define a schema using express-validator in which I set the "isStrongPassword" option. The "usernameSchema" works fine, but the "passwordSchema" doesn’t pass my entered passwords through, even if they match the requirements.
Here is my code:
userRouter.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
};
Even if I enter a password that matches the requirements, I get the following error:
{
"errors": [
{
"type": "field",
"value": "124sdjAfsd",
"msg": "Password doesn't match the requirements.",
"path": "password",
"location": "query"
}
]
}
Can someone help me with this?
2
Answers
Did some testing now (version 7.0.1)
Express validator uses the default values unless you override them, you are not passing because you didn’t override the minSymbols, so it is requiring 1 special char.
BUT If you use schema, there is a bug, you simply cannot override the default values (8 chars, 1 lower, 1 upper, 1 number and 1 special),
I can pass with this password:
aA1@1245
even with this crazy config:To be able to achieve what you want (override the minSymbol) you have to use chain validation:
When using schema validation, you need to pass options under the
options
property of the validator. They won’t work if you pass them directly to the validator.Docs