如何在express-validator中正确使用equals方法验证密码匹配?
解决密码确认字段匹配验证的问题
你完全说对了——equals('passwordConfirmation')这个写法是在把密码和**字符串字面量'passwordConfirmation'**做直接对比,而不是读取请求体里req.body.passwordConfirmation的实际值。这是因为express-validator的equals方法如果传入字符串参数,只会匹配固定文本,不会自动关联请求中的其他字段。
要实现密码与确认密码的匹配验证,你需要用**自定义验证器(custom validator)**手动对比两个字段的值,下面是两种实用的写法:
写法一:在密码字段的验证链中添加自定义检查
app.post('/users/signup', [ check('email', 'email is not valid') .isEmail() .trim(), check('password') .isLength({ min: 4 }) .withMessage('password must be at least 4 characters') .custom((passwordVal, { req }) => { // 对比密码与确认密码的取值 if (passwordVal !== req.body.passwordConfirmation) { throw new Error('Password confirmation does not match password'); } // 验证通过时返回true return true; }), ], (req, res) => { /* 你的业务处理逻辑 */ });
写法二:单独验证确认密码字段(更直观)
这种方式可以同时确保用户填写了确认密码,避免空值导致的逻辑问题:
app.post('/users/signup', [ check('email', 'email is not valid') .isEmail() .trim(), check('password') .isLength({ min: 4 }) .withMessage('password must be at least 4 characters'), // 单独验证确认密码字段 check('passwordConfirmation') .notEmpty() .withMessage('Please enter your password confirmation') .custom((confirmVal, { req }) => confirmVal === req.body.password) .withMessage('Passwords do not match'), ], (req, res) => { /* 你的业务处理逻辑 */ });
核心说明
custom验证函数接收两个参数:当前字段的取值,以及包含请求对象的上下文。通过req.body你可以轻松获取到另一个字段的值完成对比;如果对比失败,抛出Error即可返回自定义提示;验证通过时记得返回true。
内容的提问来源于stack exchange,提问作者Julian Betancourt
相关产品推荐
相关产品推荐

