Bird
Raised Fist0
Node.jsframework~20 mins

Input validation and sanitization in Node.js - Practice Problems & Coding Challenges

Choose your learning style10 modes available
Challenge - 5 Problems
🎖️
Input Validation Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
🧠 Conceptual
intermediate
1:30remaining
What is the main purpose of input sanitization in Node.js applications?

Choose the best explanation for why input sanitization is important in Node.js apps.

ATo remove or escape harmful characters from user input to prevent security issues like injection attacks.
BTo speed up the processing of user input by compressing data before use.
CTo convert all user input into uppercase letters for consistency.
DTo store user input directly into the database without any changes.
Attempts:
2 left
💡 Hint

Think about how attackers might try to harm your app through user input.

❓ state_output
intermediate
1:30remaining
What will be the output of this Node.js code snippet using the 'validator' library?

Consider the following code that validates and sanitizes an email input.

Node.js
import validator from 'validator';

const input = '  user@example.com  ';
const isValid = validator.isEmail(input);
const sanitized = validator.normalizeEmail(input);

console.log(isValid, sanitized);
Atrue user@example.com
Bfalse user@example.com
Ctrue undefined
Dfalse undefined
Attempts:
2 left
💡 Hint

Check how 'validator.isEmail' and 'validator.normalizeEmail' handle spaces.

🔧 Debug
advanced
2:00remaining
Why does this input validation code fail to reject invalid usernames?

Review the code below that tries to validate usernames to be alphanumeric and 3-10 characters long.

Node.js
function validateUsername(name) {
  const regex = /^[a-zA-Z0-9]{3,10}$/;
  return regex.test(name.trim());
}

console.log(validateUsername(' user1 '));
console.log(validateUsername('user_2'));
AIt fails because 'trim()' removes spaces inside the string, causing wrong validation.
BIt fails because the regex allows underscores, so 'user_2' passes validation incorrectly.
CIt fails because 'user_2' contains an underscore which is not allowed by the regex, so it returns false correctly.
DIt fails because the regex does not check for length, so all inputs pass.
Attempts:
2 left
💡 Hint

Look carefully at the regex pattern and the test inputs.

📝 Syntax
advanced
2:00remaining
Which option correctly sanitizes user input to prevent cross-site scripting (XSS) in a Node.js Express app?

Choose the code snippet that safely sanitizes a string input to prevent XSS attacks.

Node.js
const express = require('express');
const app = express();

app.use(express.json());

app.post('/submit', (req, res) => {
  const userInput = req.body.comment;
  // Sanitize userInput here
  res.send(`Received: ${sanitizedInput}`);
});
Aconst sanitizedInput = userInput.replace(/<script.*?>.*?<\/script>/gi, '');
Bconst sanitizedInput = userInput.trim();
Cconst sanitizedInput = userInput.toUpperCase();
Dconst sanitizedInput = userInput.replace(/</g, '&lt;').replace(/>/g, '&gt;');
Attempts:
2 left
💡 Hint

Think about how to neutralize HTML tags to stop scripts from running.

❓ component_behavior
expert
2:30remaining
What will be the behavior of this Express middleware for input validation?

Analyze the middleware that validates a JSON body field 'age' to be a positive integer.

Node.js
function validateAge(req, res, next) {
  const age = req.body.age;
  if (!Number.isInteger(age) || age <= 0) {
    return res.status(400).json({ error: 'Age must be a positive integer' });
  }
  next();
}

// Usage in Express app
// app.use(express.json());
// app.post('/user', validateAge, (req, res) => res.send('User created'));
ARequests with age as 25 will pass and respond with 'User created'.
BRequests with age as '25' (string) will pass validation and respond with 'User created'.
CRequests with age as 0 will pass validation and respond with 'User created'.
DRequests missing the age field will pass validation and respond with 'User created'.
Attempts:
2 left
💡 Hint

Consider how Number.isInteger treats strings and missing values.

Practice

(1/5)
1. What is the main purpose of input validation in a Node.js application?
easy
A. To check if the input data is correct and safe before processing
B. To store user data in the database
C. To format the output data for display
D. To speed up the server response time

Solution

  1. Step 1: Understand input validation

    Input validation ensures that the data received from users meets expected rules and is safe to use.
  2. Step 2: Identify the purpose in Node.js

    In Node.js, input validation prevents bad or harmful data from causing errors or security issues.
  3. Final Answer:

    To check if the input data is correct and safe before processing -> Option A
  4. Quick Check:

    Input validation = check data safety [OK]
Hint: Validation means checking data correctness and safety [OK]
Common Mistakes:
  • Confusing validation with data storage
  • Thinking validation formats output
  • Assuming validation improves speed
2. Which of the following is the correct way to import the express-validator middleware in a Node.js file using ES modules?
easy
A. const { check } = require('express-validator');
B. import check from 'express-validator';
C. const check = require('express-validator/check');
D. import { check } from 'express-validator';

Solution

  1. Step 1: Identify modern import syntax

    Node.js with ES modules uses import { check } from 'express-validator'; to import named exports.
  2. Step 2: Check other options

    const { check } = require('express-validator'); uses CommonJS require but destructuring is possible only if CommonJS is used; import check from 'express-validator'; imports default which express-validator does not export; const check = require('express-validator/check'); uses a wrong path.
  3. Final Answer:

    import { check } from 'express-validator'; -> Option D
  4. Quick Check:

    Use ES module import for express-validator [OK]
Hint: Use ES module import syntax with curly braces for named exports [OK]
Common Mistakes:
  • Using require instead of import in ES modules
  • Importing default instead of named export
  • Using incorrect module paths
3. Consider this Node.js code snippet using express-validator:
app.post('/submit', [
  check('email').isEmail(),
  check('age').isInt({ min: 18 })
], (req, res) => {
  const errors = validationResult(req);
  if (!errors.isEmpty()) {
    return res.status(400).json({ errors: errors.array() });
  }
  res.send('Data is valid');
});

What will be the response if the user sends { "email": "userexample.com", "age": 17 }?
medium
A. Status 400 with error about missing fields
B. Status 400 with errors about invalid email and age
C. Status 500 server error
D. Status 200 with message 'Data is valid'

Solution

  1. Step 1: Analyze validation rules

    The code checks if 'email' is a valid email and 'age' is an integer >= 18.
  2. Step 2: Check input values

    The email 'userexample.com' is missing '@', so invalid. Age 17 is less than 18, so invalid.
  3. Final Answer:

    Status 400 with errors about invalid email and age -> Option B
  4. Quick Check:

    Invalid email and age cause 400 error [OK]
Hint: Invalid inputs trigger 400 with error details [OK]
Common Mistakes:
  • Assuming invalid data passes validation
  • Confusing status codes
  • Ignoring validationResult usage
4. You wrote this code to sanitize input but it doesn't remove spaces as expected:
app.post('/data', [
  check('username').trim().escape()
], (req, res) => {
  // ...
});

What is the likely reason the spaces are not removed?
medium
A. You must call sanitize() before trim()
B. escape() removes spaces but trim() does not
C. The trim() method removes spaces only from start and end, not inside the string
D. The check() function does not support trim()

Solution

  1. Step 1: Understand trim() behavior

    The trim() method removes whitespace only from the start and end of a string, not inside it.
  2. Step 2: Check escape() effect

    escape() converts special characters but does not remove spaces inside the string.
  3. Final Answer:

    The trim() method removes spaces only from start and end, not inside the string -> Option C
  4. Quick Check:

    trim() trims edges, not inner spaces [OK]
Hint: trim() only removes spaces at string ends [OK]
Common Mistakes:
  • Expecting trim() to remove all spaces
  • Misunderstanding escape() purpose
  • Thinking check() lacks trim() support
5. You want to create a Node.js API endpoint that accepts a username and email. The username must be alphanumeric and trimmed, and the email must be valid and normalized. Which express-validator chain correctly applies validation and sanitization?
hard
A. [ check('username').trim().isAlphanumeric(), check('email').normalizeEmail().isEmail() ]
B. [ check('username').isAlphanumeric().trim(), check('email').isEmail().normalizeEmail() ]
C. [ check('username').escape().isAlphanumeric(), check('email').isEmail().trim() ]
D. [ check('username').isAlphanumeric().escape(), check('email').trim().normalizeEmail() ]

Solution

  1. Step 1: Validate username and email correctly

    Username must be alphanumeric and trimmed, so trim() before or after is okay but isAlphanumeric() must check the trimmed string. Email must be checked with isEmail() and normalized with normalizeEmail().
  2. Step 2: Analyze options

    [ check('username').trim().isAlphanumeric(), check('email').normalizeEmail().isEmail() ] applies trim() before isAlphanumeric() which ensures validation on trimmed string; [ check('username').isAlphanumeric().trim(), check('email').isEmail().normalizeEmail() ] applies isAlphanumeric() before trim(), which may validate untrimmed input; also, normalizeEmail() should come before isEmail() to validate normalized email; [ check('username').escape().isAlphanumeric(), check('email').isEmail().trim() ] escapes username unnecessarily and trims email which is not needed; [ check('username').isAlphanumeric().escape(), check('email').trim().normalizeEmail() ] escapes username and trims email incorrectly.
  3. Final Answer:

    [ check('username').trim().isAlphanumeric(), check('email').normalizeEmail().isEmail() ] -> Option A
  4. Quick Check:

    Trim before validation for username; normalize before validation for email [OK]
Hint: Trim before validation for username; normalize before validation for email [OK]
Common Mistakes:
  • Applying sanitization after validation incorrectly
  • Using escape() unnecessarily
  • Trimming email instead of normalizing
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