express-validator条件校验失效问题求助
问题根源:你的三元表达式在启动时就固定了,不是请求时动态判断
你遇到的问题是因为你的校验数组是在服务器启动时就构建完成的,而不是在每个请求进来时根据req.body.tripType的值动态决定。
具体来说,body('tripType').equals('one-way')返回的不是一个布尔值,而是一个ValidationChain对象(express-validator的校验规则实例),这个对象在JavaScript里会被当作truthy值,所以你的三元表达式永远会返回前面的校验数组——不管实际请求中的tripType是什么,这些校验都会被执行,自然达不到条件校验的效果。
正确的实现方式:用express-validator内置的.if()条件校验
express-validator专门提供了条件校验的API,推荐用.if()链式调用的方式来实现你的需求。这样每个请求进来时,都会动态判断tripType的值,再决定是否执行对应的字段校验。
以下是完整的修正代码:
const { body, validationResult } = require('express-validator'); // 定义完整的校验规则 const tripValidationRules = [ // 先校验tripType本身(可选但推荐,确保它是有效值) body('tripType') .exists({ checkFalsy: true }) .withMessage('tripType is required') .isIn(['one-way', 'round-trip']) // 根据你的业务调整可选值 .withMessage('tripType must be either "one-way" or "round-trip"'), // 仅当tripType为"one-way"时,校验currentOfficeLocation body('currentOfficeLocation') .if(body('tripType').equals('one-way')) .exists({ checkFalsy: true }) .withMessage('currentOfficeLocation: Current Office Location is required') .isInt() .withMessage('currentOfficeLocation: Current Office Location must be an integer'), // 仅当tripType为"one-way"时,校验destination body('destination') .if(body('tripType').equals('one-way')) .exists({ checkFalsy: true }) .withMessage('destination: Destination is required') .isInt() .withMessage('destination: Destination must be an integer'), // 仅当tripType为"one-way"时,校验departureDate body('departureDate') .if(body('tripType').equals('one-way')) .exists({ checkFalsy: true }) .withMessage('departureDate: Departure date is required'), // 仅当tripType为"one-way"时,校验travelreasons body('travelreasons') .if(body('tripType').equals('one-way')) .exists({ checkFalsy: true }) .withMessage('travelreasons: Travel Reasons is required') .isString() .withMessage('travelreasons: Travel Reasons should be a string'), // 仅当tripType为"one-way"时,校验accommodation body('accommodation') .if(body('tripType').equals('one-way')) .exists({ checkFalsy: true }) .withMessage('accommodation: Accommodation is required') .isInt() .withMessage('accommodation: Accommodation must be an integer'), ]; // 在路由中使用校验规则 app.post('/book-trip', tripValidationRules, (req, res) => { // 收集校验错误 const errors = validationResult(req); if (!errors.isEmpty()) { return res.status(400).json({ errors: errors.array() }); } // 校验通过,处理业务逻辑 res.status(200).json({ message: 'Trip booking validated successfully' }); });
为什么这个方法有效?
.if(conditionValidator)方法会在每个请求处理时执行传入的校验器(这里是body('tripType').equals('one-way')),只有当这个校验器通过时,后续的字段校验规则才会被执行。完全符合你需要的动态条件校验逻辑。
内容的提问来源于stack exchange,提问作者Mac Okaba
相关产品推荐
相关产品推荐

