Mongoose custom validation for password

北慕城南 提交于 2021-01-28 08:09:47

问题


I am trying to make Schema using mongoose and stuck in a point on how to apply custom validation for the password, where 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


回答1:


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
  });



回答2:


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.com/package/mongoose-custom-validators



来源:https://stackoverflow.com/questions/51766754/mongoose-custom-validation-for-password

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!