'how to validate password's length using mongoose scheme?

In my mongoose Schema i used below code for the password field..but it doesn't check for the minimum length for the password..what is wrong here??

 password:{
    type:String,
    required:true,
    match:/(?=.*\d)(?=.*[a-z])(?=.*[A-Z])/,
    minlength:5


  },


Solution 1:[1]

Hop hop hop! wait a minute. You do not store the password directly in database ; because of security concerns.


How to store passwords :

  • Get the password from the user
  • Hash it using an algorithm, like sha512 (long time ago md5 ...)
  • Store the hashed passowrd

How to check password match :

  • Get the password from the user
  • Hash it using an algorithm
  • Compare the stored password with the calculated hash

Here is a blog explaining about how to hash a password in node.js.


As example :

const crypto = require('crypto'),
    text = 'hello bob',
    key = 'mysecret key'

// create hahs
const hash = crypto.createHmac('sha512', key);

hash.update(text);

const value = hash.digest('hex');

// print result
console.log(value);

About the check of the password, you can make it inside of the function handling the hash, like :

function checkPassword(pass) {
  if (!/(?=.*\d)(?=.*[a-z])(?=.*[A-Z])/.test(pass)) {
     throw new Error('E0001');
  }

  // Password is acceptable
}

Solution 2:[2]

It is actually working correctly. You probably harshed your password in the controller and when you do this the harsh will most likely always will be greater than 8 characters in length. This is harsh is what you are checking for in the schema in the schema and since it is will always be greater than 8 then it would work fine but this is what you want. The best way is to check and enforce this is in your controller. I actually ran into this same issue today and this was how I solved it. Code example:

const registerUser = (req, res) => {
    const { email, password] = req.body;
    // check if password length is greater than 8.
    if(password.length < 8) {
        res.status(400);
        throw new Error('Password must be at least 8 characters long');
        }
    //.... the rest of your code.
}

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Orelsanpls
Solution 2 omokehinde igbekoyi