0
0
Node.jsframework~20 mins

Request validation in Node.js - Practice Problems & Coding Challenges

Choose your learning style9 modes available
Challenge - 5 Problems
🎖️
Request 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 required field is missing in this Express.js validation middleware?

Consider this Express.js middleware that validates a JSON request body for a 'username' field:

function validateUser(req, res, next) {
  if (!req.body.username) {
    return res.status(400).json({ error: 'Username is required' });
  }
  next();
}

What will the server respond if a POST request is sent without the 'username' field?

Node.js
function validateUser(req, res, next) {
  if (!req.body.username) {
    return res.status(400).json({ error: 'Username is required' });
  }
  next();
}
AThe server responds with status 200 and proceeds to the next middleware
BThe server responds with status 400 and JSON { error: 'Username is required' }
CThe server crashes with a TypeError because req.body is undefined
DThe server responds with status 500 and a generic error message
Attempts:
2 left
💡 Hint

Think about what happens when the condition !req.body.username is true.

📝 Syntax
intermediate
2:00remaining
Which option correctly validates that 'age' is a number using Joi schema?

Given the Joi validation library, which schema correctly requires 'age' to be a number?

Node.js
const Joi = require('joi');

const schema = Joi.object({
  age: ???
});
AJoi.array().required()
BJoi.string().required()
CJoi.number().required()
DJoi.boolean().required()
Attempts:
2 left
💡 Hint

Think about the data type for 'age'.

🔧 Debug
advanced
2:00remaining
Why does this Express.js validation middleware not catch missing fields?

Look at this middleware:

function validate(req, res, next) {
  if (req.body.email === undefined || req.body.password === undefined) {
    res.status(400).send('Missing fields');
  }
  next();
}

Why might it fail to stop requests missing 'email' or 'password'?

Node.js
function validate(req, res, next) {
  if (req.body.email === undefined || req.body.password === undefined) {
    res.status(400).send('Missing fields');
  }
  next();
}
ABecause next() is called even after sending a response, allowing the request to continue
BBecause req.body is always undefined in Express.js
CBecause the condition uses OR instead of AND
DBecause res.status(400).send() does not send a response
Attempts:
2 left
💡 Hint

What happens after res.status(400).send() is called?

state_output
advanced
2:00remaining
What is the value of 'errors' after running this validation with express-validator?

Given this code snippet:

const { validationResult, check } = require('express-validator');

app.post('/login', [
  check('email').isEmail(),
  check('password').isLength({ min: 6 })
], (req, res) => {
  const errors = validationResult(req);
  res.json({ errors: errors.array() });
});

If the request body is { "email": "not-an-email", "password": "123" }, what will be the JSON response?

Node.js
const { validationResult, check } = require('express-validator');

app.post('/login', [
  check('email').isEmail(),
  check('password').isLength({ min: 6 })
], (req, res) => {
  const errors = validationResult(req);
  res.json({ errors: errors.array() });
});
A[{ msg: 'Invalid value', param: 'password', location: 'body' }]
B[]
C[{ msg: 'Invalid value', param: 'email', location: 'body' }]
D[{ msg: 'Invalid value', param: 'email', location: 'body' }, { msg: 'Invalid value', param: 'password', location: 'body' }]
Attempts:
2 left
💡 Hint

Both 'email' and 'password' fail their validations.

🧠 Conceptual
expert
2:00remaining
Which statement best describes the role of middleware in request validation in Node.js frameworks?

Choose the most accurate description of how middleware functions in request validation.

AMiddleware intercepts requests before reaching route handlers to check and reject invalid data early, improving security and performance.
BMiddleware automatically fixes invalid request data and modifies it to pass validation without notifying the client.
CMiddleware delays request processing until all asynchronous database validations complete, blocking the event loop.
DMiddleware only logs validation errors but does not affect request flow or responses.
Attempts:
2 left
💡 Hint

Think about when middleware runs and what it can do with invalid data.