Consider this Express middleware using express-validator to validate a POST request body:
const { body, validationResult } = require('express-validator');
app.post('/user', [
body('username').isString().notEmpty(),
body('age').isInt({ min: 18 })
], (req, res) => {
const errors = validationResult(req);
if (!errors.isEmpty()) {
return res.status(400).json({ errors: errors.array() });
}
res.send('User created');
});What will the server respond if the request body is { "username": "alice" } (missing age)?
const { body, validationResult } = require('express-validator');
app.post('/user', [
body('username').isString().notEmpty(),
body('age').isInt({ min: 18 })
], (req, res) => {
const errors = validationResult(req);
if (!errors.isEmpty()) {
return res.status(400).json({ errors: errors.array() });
}
res.send('User created');
});Think about what happens when a required field is not present and the validation rule expects an integer.
The body('age').isInt({ min: 18 }) rule requires the age field to be an integer at least 18. If age is missing, validation fails and validationResult(req).isEmpty() returns false. The server responds with status 400 and an error message about the missing or invalid age field.
Look at this Express route with schema validation using express-validator:
app.post('/login', [
body('email').isEmail(),
body('password').isLength({ min: 6 })
], (req, res) => {
const errors = validationResult(req)
if (!errors.isEmpty()) {
return res.status(400).json({ errors: errors.array() })
}
res.send('Login successful')
})What is the syntax error in this code?
app.post('/login', [ body('email').isEmail(), body('password').isLength({ min: 6 }) ], (req, res) => { const errors = validationResult(req) if (!errors.isEmpty()) { return res.status(400).json({ errors: errors.array() }) } res.send('Login successful') })
Check if all required functions are imported before usage.
The code uses body and validationResult but does not show importing them from express-validator. Without importing, the code will throw a ReferenceError. Missing semicolons or parentheses are not syntax errors in JavaScript here, and the array brackets are properly closed.
Given this Express route:
const { body, validationResult } = require('express-validator');
app.post('/register', [
body('email').isEmail(),
body('password').isLength({ min: 8 })
], (req, res) => {
const errors = validationResult(req);
if (!errors.isEmpty()) {
return res.status(400).json({ errors: errors.array() });
}
res.send('Registration successful');
});But when sending { "email": "not-an-email", "password": "12345678" }, the server responds with 'Registration successful'. Why?
const { body, validationResult } = require('express-validator');
app.post('/register', [
body('email').isEmail(),
body('password').isLength({ min: 8 })
], (req, res) => {
const errors = validationResult(req);
if (!errors.isEmpty()) {
return res.status(400).json({ errors: errors.array() });
}
res.send('Registration successful');
});Think about how Express reads the request body before validation.
If the Express app does not use middleware like express.json() to parse JSON bodies, req.body will be undefined or empty. Validators like isEmail() then receive undefined and do not fail as expected. This causes validation to pass incorrectly.
Consider this Express route with validation:
const { body, validationResult } = require('express-validator');
app.post('/submit', [
body('title').isLength({ min: 5 }),
body('year').isInt({ min: 2000, max: 2025 })
], (req, res) => {
const errors = validationResult(req);
if (!errors.isEmpty()) {
return res.status(422).json({ errors: errors.array() });
}
res.send('Submission accepted');
});If the request body is { "title": "abc", "year": 1999 }, what is the JSON response?
const { body, validationResult } = require('express-validator');
app.post('/submit', [
body('title').isLength({ min: 5 }),
body('year').isInt({ min: 2000, max: 2025 })
], (req, res) => {
const errors = validationResult(req);
if (!errors.isEmpty()) {
return res.status(422).json({ errors: errors.array() });
}
res.send('Submission accepted');
});Check the default error messages from express-validator when no custom message is provided.
Without custom error messages, express-validator returns a default message 'Invalid value' for failed validations. Both title and year fail their checks, so the response includes errors for both with the default message.
In Express, why is it important to place schema validation middleware before the main route handler?
Think about the flow of request processing and error handling.
Validation middleware runs before the route handler to check input early. If input is invalid, it sends an error response immediately, stopping further processing. This prevents the route handler from running with bad data. Validation middleware does not modify data or send success responses automatically.