最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Mongoose custom validation for password - Stack Overflow

programmeradmin3浏览0评论

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

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

Share Improve this question edited Jan 12, 2022 at 8:58 Yilmaz 50.1k19 gold badges218 silver badges271 bronze badges asked Aug 9, 2018 at 12:14 abhigyan nayakabhigyan nayak 1,4448 gold badges26 silver badges38 bronze badges
Add a ment  | 

2 Answers 2

Reset to default 4

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 plex 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./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
  });

You need to pass password a validate property with a validator function

password: {
  type: String,
  validate: {
    validator: isValidPassword,
    message: 'Password must be... '
  }
}

I have created this mongoose-custom-validators module with those requirements in mind. Check out the isValidPassword validator from this module. The documentation should be thorough on the usage.

https://www.npmjs./package/mongoose-custom-validators

发布评论

评论列表(0)

  1. 暂无评论