如何使用express-validator npm验证密码

Sun*_*rma 9 regex validation node.js express

我正在使用node,express web模块编写rest API.为了验证我使用快速验证器 npm.我想在密码字段上应用一些验证规则.

如何使用express-validator实现它?

我想要将密码应用于哪些验证规则:

  1. 最少8个字符.
  2. 至少一个大写.
  3. 至少一个小写字母.
  4. 至少有一个特殊字符.

我在这个链接中读到有一个名为regex()的函数.所以我尝试了但根本没有工作.

我的方法:

req.check("password", "Password should be combination of one uppercase , one lower case, one special char, one digit and min 8 , max 20 char long").regex("/^(?=.*\d)(?=.*[a-z])(?=.*[A-Z])[0-9a-zA-Z]{8,}$/", "i");
Run Code Online (Sandbox Code Playgroud)

错误

在此输入图像描述

express-js中, 他们列出了所有方法,但没有找到解决我问题的方法/技巧.

rob*_*lep 13

您所指的链接已近3年.从那以后,API发生了validator变化.

要检查正则表达式,请使用.matches():

req.check("password", "...").matches(/^(?=.*\d)(?=.*[a-z])(?=.*[A-Z])[0-9a-zA-Z]{8,}$/, "i");
Run Code Online (Sandbox Code Playgroud)


tbk*_*ing 7

我相信接受的答案已经过时了。RegExpexpress-validator不是 2017 年验证密码的最佳方法,因为正则表达式的晦涩使得应用程序无法维护且容易出现错误。

password-validator使定义密码规则和维护它们变得容易。这是一个示例:

var passwordValidator = require('password-validator');

var schema = new passwordValidator();

schema
  .is().min(8)
  .is().max(100)
  .has().uppercase()
  .has().lowercase();

console.log(schema.validate(req.body.password)); // prints a boolean
Run Code Online (Sandbox Code Playgroud)

PS:我是password-validator的作者。


Huh*_*gut 7

对此有一个新的解决方案。从文档中:

检查密码是否强。允许自定义要求或评分规则。如果 returnScore 为 true,则该函数返回密码的整数分数而不是布尔值。默认选项:

body('password').isStrongPassword({
  minLength: 8,
  minLowercase: 1,
  minUppercase: 1,
  minNumbers: 1,
  minSymbols: 1,
  returnScore: false,
  pointsPerUnique: 1,
  pointsPerRepeat: 0.5,
  pointsForContainingLower: 10,
  pointsForContainingUpper: 10,
  pointsForContainingNumber: 10,
  pointsForContainingSymbol: 10,
})
Run Code Online (Sandbox Code Playgroud)

  • 我又找到了:https://github.com/validatorjs/validator.js#validators (3认同)

小智 5

使用express-validator的内置验证器,我可以使用内置验证器而无需正则表达式来检查密码。

const validateStrongPassword = body("password")
  .isString()
  .isLength({ min: 8 })
  .not()
  .isLowercase()
  .not()
  .isUppercase()
  .not()
  .isNumeric()
  .not()
  .isAlpha();
Run Code Online (Sandbox Code Playgroud)

这将验证密码中是否至少有一个非字母字符、一个小写字母、一个大写字母、最小长度以及是否包含字母。