Consider an Express app that accepts user data. Why must we validate inputs before processing?
Think about what happens if harmful data reaches your database or server.
Input validation stops harmful or unexpected data from causing security problems or crashes. It ensures only safe, expected data is processed.
Given an Express route that saves user input to a database without validation, what is a likely outcome?
app.post('/submit', (req, res) => { const userInput = req.body.data; database.save(userInput); res.send('Saved'); });
Think about what happens if users send unexpected or malicious data.
Without validation, harmful data can be saved, leading to security risks like injection attacks or corrupted data.
Choose the middleware snippet that properly validates a JSON field 'age' to be a positive integer.
const express = require('express');
const app = express();
app.use(express.json());Check both type and value to ensure age is a positive number.
Option A checks that 'age' is a number and greater than zero, ensuring valid input. Others miss type or value checks.
Identify the reason this validation code does not reject invalid input:
app.post('/data', (req, res) => { if (req.body.email && req.body.email.includes('@')) { res.send('Valid email'); } else { res.status(400).send('Invalid email'); } });
What happens if the client sends no 'email' field?
If 'email' is missing, calling includes() on undefined causes a runtime error, crashing the app.
Given this Express route with input validation, what response does the server send when 'username' is missing?
app.post('/register', (req, res) => { const { username, password } = req.body; if (!username || username.length < 3) { return res.status(422).json({ error: 'Username too short or missing' }); } if (!password || password.length < 6) { return res.status(422).json({ error: 'Password too short or missing' }); } res.status(200).json({ message: 'User registered' }); });
Check the validation order and conditions for missing 'username'.
If 'username' is missing, the first if condition triggers and returns a 422 error with the appropriate message.