express - Express-validator:条件验证
问题描述
您好,我想在快速验证中集成 IF...else 语句,但我在运行时面临。
我知道我可以使用 Oneof() 但它返回TypeError: chain.run is not a function
验证器.js
const { validationResult, check } = require('express-validator');
exports.surveyValidation =[
[ [check('question.label').isLength({min:5}),
check('question.mandatory').isBoolean()] ,
check('question.min').isNumeric(), check('question.max').isNumeric()]
]
exports.validate =(req, res, next)=>{
const errors = validationResult(req);
console.log(`errors`, errors)
if (!errors.isEmpty()) {
console.log(`errors`, errors)
return res.status(422).json({ errors: errors.array() });
}
return next()
}
可以有一个罐子,我在其中调用没有question.min 和 question.max的路线,所以我想仅在它存在的情况下验证该字段,否则我可以毫无问题地继续。
因为验证是用来存储问题的,而封闭的问题没有这个键
api.js
app.post("/api/question",surveyValidation, validate ,(req, res) => {
surveyDao.question(req.body.question, req.body.idSurvey)
.then(result => {
res.json(result)
})
.catch(err => {
console.log(`err`, err)
res.status(500).send(err)
})
})