Express Validator适配自定义嵌套请求体结构问题咨询
Hey there! I totally get where you're stuck—your POST request body nests all required fields under the data key, but your current validation rules are checking for fields directly at the top level of req.body instead of inside req.body.data. Let's get this sorted out quickly.
Step 1: Update Validation Rules to Target Nested Fields
Express Validator supports dot notation to access nested properties in the request body. All you need to do is prefix each field name with data. in your check() calls. Also, I noticed a small issue in your original rules: you're using .isEmpty() which validates that a field is empty (the opposite of what you want!). Swap that for .notEmpty() to ensure fields are present and not blank.
Here's your updated validation rules file:
const { check, validationResult } = require('express-validator'); const createPostRules = [ // Validate nested fields using dot notation check('data.local_db_path') .notEmpty() .withMessage('Post Key is missing'), check('data.source_type') .notEmpty() .withMessage('Post source type missing') .isIn(['google', 'imdb']) .withMessage('Invalid source type'), check('data.source_id') .notEmpty() .withMessage('Post source key missing'), check('data.box_ids') .notEmpty() .withMessage('Box Information is missing') .isArray() .withMessage('Box IDs must be an array') // Optional: Add array type validation for extra rigor ]; module.exports = { createPostRules };
Step 2: Keep Your Controller Logic (Almost) the Same
You don't need big changes to your controller—validationResult(req) will automatically pick up errors from nested fields as long as your rules use the correct dot notation. Just make sure you access the nested data from req.body.data when processing the request:
const { validationResult } = require('express-validator'); exports.createPost = (req, res) => { // Check for validation errors const errors = validationResult(req); if (!errors.isEmpty()) { return res.status(400).json({ errors: errors.array() }); } // Access the nested post data safely const postData = req.body.data; // Your existing logic to create the post goes here... res.status(201).json({ message: 'Post created successfully', data: postData }); };
Why This Works
Express Validator parses the dot notation in check() to traverse the request body object. So check('data.local_db_path') directly maps to req.body.data.local_db_path, which is exactly where your fields live in the request.
That's it! Your validation should now correctly validate all nested fields in your POST request body.
内容的提问来源于stack exchange,提问作者Rizwan Saleem

