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

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


Here is how i solved the issue:if You are using joi@14.3.1 or older then install joi-password-complexity@2.0.1 then try this code:

User.js modelconst mongoose = require("mongoose");const Joi = require("joi");const PasswordComplexity = require("joi-password-complexity");const userSchema = new mongoose.Schema({  name: {    type: String,    required: true,    trim: true  },  email: { type: String, required: true, unique: true },  password: { type: String, required: true }});const User = mongoose.model("User", userSchema);function validateUser(user) {  const schema = {    name: Joi.string()      .min(3)      .max(50)      .required(),    email: Joi.string()      .email()      .max(255)      .required(),    password:  new PasswordComplexity({    min: 8,    max: 25,    lowerCase: 1,    upperCase: 1,    numeric: 1,    symbol: 1,    requirementCount: 4  });  };  return Joi.validate(user, schema);}module.exports.validate = validateUser;module.exports.User = User;

This will validate password complexity but for making password REQUIRED you have to validate it in your route...

Users.js routeconst _ = require("lodash");const express = require("express");const { User, validate } = require("../models/user");const router = express.Router();//POSTrouter.post("/", async (req, res) => {  const { error } = validate(req.body);  if (error) return res.status(400).send(error.details[0].message);  //  if (!req.body.password) return res.status(400).send("Password is required..");  let user = await User.findOne({ email: req.body.email });  if (user) return res.status(400).send("User already registered..");  user = new User(_.pick(req.body, ["name", "email", "password"]));  await user.save();  res.send(_.pick(user, ["_id", "name", "email"]));});module.exports = router;


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) // This is not working  });  // note that we call schema.validate instead of Joi.validate  // (which doesn't seem to exist anymore)  return schema.validate(user);}


I had to add .default to import the function that returns the Joi object. Using Joi 17.3.0 and joi-password-complexity 5.0.1, this is what worked for me:

const passwordComplexity = require('joi-password-complexity').default;const schema = Joi.object({  email: Joi.string().min(5).max(255).required().email(),  password: passwordComplexity().required(),});