简体   繁体   中英

Sequelize password validation using len and setter fails

I set up the password field like below:

password: {
   type: Sequelize.STRING,
   validate: {
      len: { 
         args: [7, 42],
         msg: "The password length should be between 7 and 42 characters."
      }
   }
}

This works. However, when I add the set handler, to convert the password into an md5 hash, the validation fails always (it ends with that message I set up above):

password: {
   type: Sequelize.STRING,
   validate: {
      len: { 
         args: [7, 42],
         msg: "The password length should be between 7 and 42 characters."
      }
   },
   set (pass, key) {
      // `key` is "password" here
      this.setDataValue(key, md5(pass));
   }
}

It seems to me like len and set don't like each another, but I can't understand why.

How to solve this?

I also had this same problem, and I ended up creating a validation within the setter function:

set(value) {
  if (value.length >= 8 && value.length <= 20) {
    this.setDataValue('password', bcrypt.hashSync(value, 10));
  } else {
    throw new Error('Your password should be between 8-20 characters!');
  }
}

This worked for my purposes.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM