我正在尝试验证登录请求,其中该登录请求接受可以为电子邮件或用户名的用户名以及密码。如何使用Express-Validator做到这一点?
我正在阅读文档,验证器的工作方式是您必须将数据作为第二个参数传递。 我不确定如何检查用户名或密码也可以做到这一点。
router.post("/", (req, res) => {
const { nickname, password } = req.body;
// Create a new object based on email or username
const login = {};
if (nickname.indexOf('@') === -1) {
login.nickname = nickname;
} else {
login.email = nickname;
}
login.password = password;
// JWT Sign...
});
使用验证器,我还要检查它是否是
尝试
router.post("/", (req, res) => {
const { nickname, password } = req.body;
// Create a new object based on email or username
const login = {};
if (nickname.indexOf('@') === -1) {
check('nickname').isLength({ 'min': 3 });
login.nickname = nickname;
} else {
check('nickname').isEmail();
login.email = nickname;
}
login.password = password;
const errors = validationResult(req);
if (!errors.isEmpty()) {
return res.status(422).json({ errors: errors.array() });
}
});
似乎验证器没有用。
答案 0 :(得分:1)
您可以使用oneOf
来验证用户名或电子邮件。这是一个示例:
const util = require('util');
const { validator } = require('express-validator');
const { check, oneOf, validationResult } = require('express-validator/check');
const validation = [
oneOf([
check('nickname')
.exists()
.withMessage('nickname is required')
.isLength({ min: 3 })
.withMessage('wrong nickname length'),
check('nickname')
.exists()
.withMessage('nickname is required')
.isEmail()
.withMessage('nickname not valid'),
]),
check('password')
.exists()
.withMessage('password is required')
];
function handleValidationErrors(req, res, next) {
const errors = validationResult(req);
if (!errors.isEmpty()) {
console.log(util.inspect(errors.array()));
return res.status(422).json({ errors: errors.array() });
}
next();
};
router
.post('/', validation, handleValidationErrors,
(req, res) => {
const isEmail = validator.isEmail(req.body.nickname);
res.status(200).json({ isEmail });
});
nickname
可以是长度大于3的字符串,也可以是电子邮件。始终需要密码。验证程序数组作为中间件数组传递给router.post()
。 handleValidationErrors()
只是一个辅助功能。您可以在实际逻辑中使用相同的逻辑,也可以根据需要使用try-catch。
我在主回调中使用isEmail()
来检查它是用户名还是电子邮件。然后,我在回复中发送。您可以根据自己的喜好使用isEmail
。
答案 1 :(得分:0)
I suggest you to use Joi validator (npm install joi --save
)
const Joi = require('joi');
const validateRequest = (schema) => async (req, res, next) => {
const { error } = Joi.validate(req.body, schema);
if (error) {
throw new Error(error);
}
return next();
};
const validationSchema = Joi.object().keys({
nickname: [Joi.string().email(), Joi.string().min(3)],
password: Joi.string().required(),
}),
router.post('/', validateRequest(validationSchema), (req, res) =>
// rest of your code
But a quick fix for your code would be to pass variable nickname
to check
and not string:
check(nickname).isLength({ 'min': 3 });
check(nickname).isEmail();
答案 2 :(得分:0)
尝试一下,
npm install validator
和
npm install express-validator
然后
const {check, oneOf } = require('express-validator')
const validator = require('validator')
在您的验证功能中尝试一下,
oneOf([
check('nickname').isEmail(),
check('nickname').not().isEmpty().isString().custom((value, {req})=>{
if(!validator.isEmail(value)){
req.body.flag = true
// you can handler your req.body here ....
}
return true
})
]