0
0
Node.jsframework~20 mins

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

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