Mongoose custom validation for password

I am trying to make Schema using mongoose and stuck in a point on how to apply custom validation for the password, where the password contains:

  • one special character

  • password should have one lowercase and one uppercase character

  • password should have a length of more than 6

Here is the Schema:

const mongoose = require('../db/mongoose');
const validator = require('validator');

const UserSchema = new mongoose.Schema({
    email: {
        type: String,
        validate: {
            validator: validator.isEmail()
        }
    },
    password: {
        type: String,
        minlength: 6,
    }
});

Thanks


Since you are not supposed to save plain password in your database, it does not make sense to validate the password in the database. Because you should hash the password first and then save it. hashed password will be a complex string that most likely will pass the validation to be saved in database.

So you have to validate the password in client side. for this you can use joi npm package.

https://www.npmjs.com/package/@hapi/joi

this is how you can implement it.

userModel.js //should be in models folder

 const Joi = require('@hapi/joi');
 const mongoose = require("mongoose");

 //you defined your schema above, it should be **lowercase** 
 //here is the model, model should start capital letter 
 const User=mongoose.model("User",userSchema)

function validateUser(user) {
  const schema = Joi.object().keys({
    email: Joi.string()
      .min(8)
      .max(50)
      .required()
      .email(),
    password: Joi.string()
      .min(6)
      .required()
      .max(20)
      .regex(/^(?=.*\d)(?=.*[a-z])(?=.*[A-Z])(?=.*[^a-zA-Z0-9]).{8,1024}$/) //special/number/capital
  });
  return Joi.validate(user, schema);
}

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

i will demonstrate how to use this function inside a post router.

userRoute.js

//import model and validate func
const { User, validate } = require("/models/user"); 

router.post("/", async (req, res) => {
  //validating the request here
  const { error } = validate(req.body);
  if (error) res.status(400).send(error.details[0].message);

  //i used this code to show you how to use validate function
  //i am not sure what is your project about
  });