Search code examples
node.jsmongodbmongoosepasswordsjoi

How can I implement joi-password-complexity in Joi validation?


I want to enforce password complexity by using the joi-password-complexity package when users register.

https://github.com/kamronbatman/joi-password-complexity

I tried but I got the following error:

(node:14872) UnhandledPromiseRejectionWarning: AssertionError [ERR_ASSERTION]: Invalid schema content: (password.$_root.alternatives)

This is the code I'm using:

const mongoose = require("mongoose");
const Joi = require("joi");
const passwordComplexity = require("joi-password-complexity");

const complexityOptions = {
  min: 5,
  max: 250,
  lowerCase: 1,
  upperCase: 1,
  numeric: 1,
  symbol: 1,
  requirementCount: 2,
};

const userSchema = new mongoose.Schema({
  name: {
    type: String,
    minlenght: 1,
    maxlength: 55,
    required: true
  },
  email: {
    type: String,
    minlength: 5,
    maxlength: 255,
    unique: true,
    required: true
  },
  password: {
    type: String,
    minlength: 5,
    maxlength: 1024,
    required: true
  }
})

const User = mongoose.model("User", userSchema);

function validateUser(user) {
  const schema = {
    name: Joi.string().min(1).max(55).required(),
    email: Joi.string().min(5).max(255).required().email(),
    password: passwordComplexity(complexityOptions) // This is not working
  }
  return Joi.validate(user, schema);
}

exports.User = User;
exports.validate = validateUser;

I also tried to follow this example: https://forum.codewithmosh.com/d/215-joi-password-complexity-problem but it seems outdated since the "new" keyword will throw another error (not a constructor).

Any help is appreciated!


Solution

  • Couldn't reproduce your exact error, but I had the thing working this way:

    • @hapi/joi: ^17.1.0 (latest at the time of the writing, also works with 16.1.8)
    • joi-password-complexity: ^4.0.0 (latest as well)

    Code:

    function validateUser(user) {
      // no change here
      const schema = Joi.object({
        name: Joi.string().min(1).max(55).required(),
        email: Joi.string().min(5).max(255).required().email(),
        password: passwordComplexity(complexityOptions)
      });
      // note that we call schema.validate instead of Joi.validate
      // (which doesn't seem to exist anymore)
      return schema.validate(user);
    }