0
0
Expressframework~20 mins

Schema validation in Express - Practice Problems & Coding Challenges

Choose your learning style9 modes available
Challenge - 5 Problems
🎖️
Schema Validation Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
component_behavior
intermediate
2:00remaining
What happens when a request body misses a required field in this Express schema validation?

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)?

Express
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');
});
AResponds with status 400 and an error about missing 'age' field
BResponds with status 200 and message 'User created'
CResponds with status 500 due to server error
DResponds with status 400 and an error about missing 'username' field
Attempts:
2 left
💡 Hint

Think about what happens when a required field is not present and the validation rule expects an integer.

📝 Syntax
intermediate
2:00remaining
Identify the syntax error in this Express schema validation middleware

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?

Express
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')
})
AMissing semicolons after statements inside the route handler
BMissing parentheses after 'validationResult' call
CMissing import of 'body' and 'validationResult' from 'express-validator'
DMissing closing bracket for the array of validation middlewares
Attempts:
2 left
💡 Hint

Check if all required functions are imported before usage.

🔧 Debug
advanced
2:00remaining
Why does this Express schema validation not catch invalid email input?

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?

Express
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');
});
AThe isEmail() validator is not working because the password is valid
BThe route handler does not return after sending the error response
CThe validationResult is not called correctly
DThe request body is not parsed as JSON before validation, so fields are undefined
Attempts:
2 left
💡 Hint

Think about how Express reads the request body before validation.

state_output
advanced
2:00remaining
What is the output of this Express validation error response?

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?

Express
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');
});
A{"errors":[{"value":"abc","msg":"Title must be at least 5 characters long","param":"title","location":"body"},{"value":1999,"msg":"Year must be between 2000 and 2025","param":"year","location":"body"}]}
B{"errors":[{"value":"abc","msg":"Invalid value","param":"title","location":"body"},{"value":1999,"msg":"Invalid value","param":"year","location":"body"}]}
C{"errors":[{"value":"abc","msg":"Too short","param":"title","location":"body"}]}
D{"errors":[]}
Attempts:
2 left
💡 Hint

Check the default error messages from express-validator when no custom message is provided.

🧠 Conceptual
expert
2:00remaining
Which option best explains why schema validation middleware must run before route handlers in Express?

In Express, why is it important to place schema validation middleware before the main route handler?

ABecause validation middleware checks and rejects invalid input early, preventing the handler from processing bad data
BBecause validation middleware modifies the request body to match the schema before the handler uses it
CBecause route handlers cannot access <code>req.body</code> unless validation middleware runs first
DBecause validation middleware automatically sends success responses if validation passes, so handlers are skipped
Attempts:
2 left
💡 Hint

Think about the flow of request processing and error handling.