Bird
Raised Fist0
Node.jsframework~20 mins

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

Choose your learning style10 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.

Practice

(1/5)
1. What is the main purpose of request validation in a Node.js app?
easy
A. To store data in the database
B. To speed up the server response time
C. To check incoming data before using it
D. To create new routes automatically

Solution

  1. Step 1: Understand request validation

    Request validation means checking the data sent by users before the app uses it.
  2. Step 2: Identify the main goal

    The goal is to ensure data is safe and correct to avoid errors or security issues.
  3. Final Answer:

    To check incoming data before using it -> Option C
  4. Quick Check:

    Request validation = check data first [OK]
Hint: Validation means checking data before use [OK]
Common Mistakes:
  • Thinking validation speeds up server
  • Confusing validation with data storage
  • Assuming validation creates routes
2. Which code snippet correctly uses express-validator to check if 'email' is valid?
easy
A. validateEmail('email').isValid()
B. validate('email').isEmail()
C. checkEmail('email').validate()
D. check('email').isEmail()

Solution

  1. Step 1: Recall express-validator syntax

    express-validator uses check('fieldName').validationMethod() to validate fields.
  2. Step 2: Match correct method for email

    The method is isEmail() to check if the input is a valid email.
  3. Final Answer:

    check('email').isEmail() -> Option D
  4. Quick Check:

    express-validator uses check() + isEmail() [OK]
Hint: Use check('field').isEmail() for email validation [OK]
Common Mistakes:
  • Using validate() instead of check()
  • Wrong method names like validateEmail()
  • Mixing method order or names
3. Given this code, what will be the output if the request body has { email: 'not-an-email' }?
app.post('/signup', [
  check('email').isEmail(),
  (req, res) => {
    const errors = validationResult(req);
    if (!errors.isEmpty()) {
      return res.status(400).json({ errors: errors.array() });
    }
    res.send('Success');
  }
]);
medium
A. Response with status 400 and error details
B. Response with 'Success' message
C. Server crashes with an error
D. Response with status 200 and empty body

Solution

  1. Step 1: Check validation rule

    The rule check('email').isEmail() requires a valid email format.
  2. Step 2: Analyze input and error handling

    The input 'not-an-email' fails isEmail(), so errors.isEmpty() is false, triggering status 400 with error details.
  3. Final Answer:

    Response with status 400 and error details -> Option A
  4. Quick Check:

    Invalid email triggers 400 error [OK]
Hint: Invalid input triggers 400 error with details [OK]
Common Mistakes:
  • Assuming success response on invalid input
  • Expecting server crash on validation fail
  • Ignoring error handling logic
4. Identify the error in this validation middleware:
app.post('/login', [
  check('password').isLength({ min: 6 }),
  (req, res) => {
    const errors = validationResult;
    if (!errors.isEmpty()) {
      return res.status(422).json({ errors: errors.array() });
    }
    res.send('Logged in');
  }
]);
medium
A. validationResult is not called with req, so errors is not an object with isEmpty()
B. isLength should be isMinLength for password check
C. Missing next() call to continue middleware chain
D. Response status 422 is invalid for validation errors

Solution

  1. Step 1: Check usage of validationResult

    validationResult must be called as validationResult(req) to get errors from the request.
  2. Step 2: Identify the mistake in code

    The code assigns errors = validationResult without calling it, so errors is not an object with isEmpty().
  3. Final Answer:

    validationResult is not called with req, so errors is not an object with isEmpty() -> Option A
  4. Quick Check:

    Call validationResult(req) to get errors [OK]
Hint: Always call validationResult(req) to get errors [OK]
Common Mistakes:
  • Forgetting to call validationResult as a function
  • Using wrong validation method names
  • Confusing middleware flow with next()
5. You want to validate a request body with fields 'username' (required, min 3 chars) and 'age' (optional, must be a number if present). Which express-validator setup is correct?
hard
A. [check('username').optional().isLength({ min: 3 }), check('age').isNumeric()]
B. [check('username').isLength({ min: 3 }).notEmpty(), check('age').optional().isNumeric()]
C. [check('username').isLength({ min: 3 }), check('age').notEmpty().isNumeric()]
D. [check('username').notEmpty(), check('age').optional().isString()]

Solution

  1. Step 1: Validate 'username' requirements

    Username is required and must have at least 3 characters, so use notEmpty() and isLength({ min: 3 }).
  2. Step 2: Validate 'age' requirements

    Age is optional but if present must be numeric, so use optional() and isNumeric().
  3. Final Answer:

    [check('username').isLength({ min: 3 }).notEmpty(), check('age').optional().isNumeric()] -> Option B
  4. Quick Check:

    Required username + optional numeric age = [check('username').isLength({ min: 3 }).notEmpty(), check('age').optional().isNumeric()] [OK]
Hint: Use optional() for optional fields, notEmpty() for required [OK]
Common Mistakes:
  • Marking required fields as optional
  • Not chaining optional() before other checks
  • Using wrong validators like isString() for numbers
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard