Search code examples
javascriptnode.jsexpressvalidationexpress-validator

Use isStrongPassword in validation schema


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?


Solution

  • 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.

    isStrongPassword: {
      options: {
        minLength: 8,
        minLowercase: 1,
        minUppercase: 1,
        minNumbers: 1
      }
    }
    

    Docs