cho*_*ovy 10 validation node.js express
我在快递3.x上使用快递验证器 - 当用户更改密码或注册新帐户时,他们必须输入两次密码.
如果两个密码(两个字符串)不匹配,我将如何编写一个自定义验证器,将错误发送到快速验证器中的错误堆栈?
像这样的东西:
req.assert('password1', 'Passwords do not match').isIdentical(password1, password2);
var mappedErrors = req.validationErrors(true);
Run Code Online (Sandbox Code Playgroud)
cho*_*ovy 17
我找到了答案
req.assert('password2', 'Passwords do not match').equals(req.body.password1);
var mappedErrors = req.validationErrors(true);
Run Code Online (Sandbox Code Playgroud)
小智 8
这是我找到的答案
const { body } = require('express-validator/check');
app.post('/user', body('passwordConfirmation').custom((value, { req }) => {
if (value !== req.body.password) {
throw new Error('Password confirmation does not match password');
}
}), (req, res) => {
// Handle the request
});`
Run Code Online (Sandbox Code Playgroud)
检查此文档https://express-validator.github.io/docs/custom-validators-sanitizers.html
这一个有效!
req.checkBody('password2','Passwords do not match.').equals(req.body.password1);
var errors = req.validationErrors();
Run Code Online (Sandbox Code Playgroud)
注意 在这种情况下的使用checkBody()
这是一个更干净、更完整的解决方案:
文件:routes/auth.route.js
const express = require('express');
const controller = require('../controllers/auth.controller');
const isAuth = require('../middleware/isAuth');
const {body} = require('express-validator');
const router = express.Router();
// Validators Definition:
.
.
.
const registerValidators = [
.
.
.
body('password')
.exists({checkFalsy: true}).withMessage('You must type a password'),
body('confirmedPassword')
.exists({checkFalsy: true}).withMessage('You must type a confirmation password')
.custom((value, {req}) => value === req.body.password).withMessage("The passwords do not match"),
];
// Routes Definition:
.
.
.
router.post('/register', ...registerValidators, controller.register);
module.exports.routes = router;
Run Code Online (Sandbox Code Playgroud)
笔记:
传递到自定义验证器的匿名函数内收到的参数的名称必须是req。不是“请求”,也不是其他任何东西。否则就行不通。
| 归档时间: |
|
| 查看次数: |
6118 次 |
| 最近记录: |