Bird
Raised Fist0
Expressframework~10 mins

Manual validation patterns in Express - Step-by-Step Execution

Choose your learning style10 modes available

Start learning this pattern below

Jump into concepts and practice - no test required

or
Recommended
Test this pattern10 questions across easy, medium, and hard to know if this pattern is strong
Concept Flow - Manual validation patterns
Receive HTTP Request
Extract Input Data
Check Each Field Manually
If Invalid
YesSend Error Response
End Request
If Valid
NoProcess Request
Send Success Response
This flow shows how Express manually checks input fields, sends errors if invalid, or processes the request if valid.
Execution Sample
Express
app.post('/user', (req, res) => {
  const { name, age } = req.body;
  if (!name) return res.status(400).send('Name required');
  if (typeof age !== 'number') return res.status(400).send('Age must be number');
  res.send('User created');
});
This code manually checks if 'name' exists and 'age' is a number, sending errors or success accordingly.
Execution Table
StepActionInput DataValidation CheckResultResponse Sent
1Receive request{ name: 'Alice', age: 30 }Check name existsValidNo
2Check age type{ name: 'Alice', age: 30 }age is numberValidNo
3All valid{ name: 'Alice', age: 30 }N/APassUser created
4Receive request{ age: 30 }Check name existsInvalidName required
5Receive request{ name: 'Bob', age: 'old' }Check name existsValidNo
6Check age type{ name: 'Bob', age: 'old' }age is numberInvalidAge must be number
💡 Execution stops when an invalid field is found and error response is sent.
Variable Tracker
VariableStartAfter Step 1After Step 2After Step 3After Step 4After Step 5After Step 6
nameundefined'Alice''Alice''Alice'undefined'Bob''Bob'
ageundefined30303030'old''old'
responseSentfalsefalsefalsetruetruefalsetrue
Key Moments - 2 Insights
Why does the code send an error immediately after finding a missing 'name'?
Because the validation checks each field step-by-step and stops at the first invalid one, sending an error response immediately (see execution_table row 4).
What happens if 'age' is a string instead of a number?
The code detects the invalid type in the second check and sends an error response without processing further (see execution_table row 6).
Visual Quiz - 3 Questions
Test your understanding
Look at the execution table, what is the response sent at step 3?
A"Name required"
B"Age must be number"
C"User created"
DNo response sent
💡 Hint
Check the 'Response Sent' column at step 3 in the execution_table.
At which step does the validation detect a missing 'name' field?
AStep 4
BStep 5
CStep 2
DStep 6
💡 Hint
Look for the row where 'Validation Check' is 'Check name exists' and 'Result' is 'Invalid'.
If the input had name='Eve' and age=25, how would the responseSent variable change after step 3?
AIt would be false
BIt would be true
CIt would be undefined
DIt would be an error
💡 Hint
See variable_tracker for 'responseSent' after valid inputs at step 3.
Concept Snapshot
Manual validation in Express:
- Extract input from req.body
- Check each field with if statements
- Send error response immediately if invalid
- Continue processing if all valid
- Simple, clear, but can get verbose
- Good for small forms or quick checks
Full Transcript
This visual trace shows how manual validation patterns work in Express. When a request arrives, the server extracts input data like 'name' and 'age'. It checks each field one by one. If a field is missing or wrong type, it sends an error response immediately and stops. If all fields are valid, it processes the request and sends success. The execution table shows each step with input, checks, and responses. The variable tracker follows how variables like 'name', 'age', and 'responseSent' change. Key moments explain why errors stop execution early and how type checks work. The quiz tests understanding of when errors occur and what responses are sent. This pattern is simple and clear, good for beginners learning validation in Express.

Practice

(1/5)
1. What is the main purpose of manual validation in Express route handlers?
easy
A. To check user input step-by-step and catch bad data early
B. To automatically generate database schemas
C. To speed up server response time by skipping checks
D. To style the user interface dynamically

Solution

  1. Step 1: Understand manual validation role

    Manual validation means checking user input carefully in your code before using it.
  2. Step 2: Identify the main goal

    The goal is to catch bad or incorrect data early to keep the app safe and user-friendly.
  3. Final Answer:

    To check user input step-by-step and catch bad data early -> Option A
  4. Quick Check:

    Manual validation = catch bad data early [OK]
Hint: Manual validation means checking input carefully yourself [OK]
Common Mistakes:
  • Thinking validation auto-generates database code
  • Believing validation speeds up server by skipping checks
  • Confusing validation with UI styling
2. Which of the following is the correct way to manually validate that a request body has a non-empty 'username' field in Express?
easy
A. if (req.body.username === undefined) { next(); }
B. if (!req.body.username) { res.status(400).send('Username required'); }
C. if (req.body.username.length === 0) { res.sendStatus(200); }
D. if (req.body.username == null) { res.redirect('/'); }

Solution

  1. Step 1: Check for missing or empty username

    Using !req.body.username checks if username is missing or empty string.
  2. Step 2: Respond with error status and message

    Sending status 400 with message 'Username required' correctly informs client of bad input.
  3. Final Answer:

    if (!req.body.username) { res.status(400).send('Username required'); } -> Option B
  4. Quick Check:

    Check missing username and send 400 error [OK]
Hint: Use if (!field) to check missing or empty string [OK]
Common Mistakes:
  • Using next() instead of sending error response
  • Sending 200 OK on invalid input
  • Redirecting instead of responding with error
3. Consider this Express route snippet:
<pre>app.post('/submit', (req, res) => { if (typeof req.body.age !== 'number' || req.body.age < 18) { return res.status(400).send('Age must be 18 or older'); } res.send('Welcome!'); });
What will be the response if the client sends {"age": 16} in JSON body?
medium
A. Status 500 server error
B. Status 200 with message 'Welcome!'
C. Status 400 with message 'Age must be 18 or older'
D. No response, request hangs

Solution

  1. Step 1: Check age type and value

    The code checks if age is not a number or less than 18. Here age is 16, a number but less than 18.
  2. Step 2: Return 400 error with message

    Since age < 18, the code returns status 400 with message 'Age must be 18 or older'.
  3. Final Answer:

    Status 400 with message 'Age must be 18 or older' -> Option C
  4. Quick Check:

    Age 16 triggers 400 error [OK]
Hint: Check conditions carefully to predict response status [OK]
Common Mistakes:
  • Assuming 16 passes validation
  • Expecting 200 OK instead of error
  • Thinking server crashes on invalid input
4. Identify the bug in this manual validation code snippet:
app.post('/login', (req, res) => {
  if (req.body.password.length < 8) {
    res.status(400).send('Password too short');
  }
  res.send('Login successful');
});
medium
A. Missing return after sending error response causes double response
B. Password length check should be > 8, not < 8
C. Should use req.query instead of req.body
D. res.send should be res.json for JSON response

Solution

  1. Step 1: Analyze error response flow

    The code sends error response if password is too short but does not stop execution.
  2. Step 2: Identify missing return causes double response

    Without return, the code continues and sends 'Login successful' response, causing error.
  3. Final Answer:

    Missing return after sending error response causes double response -> Option A
  4. Quick Check:

    Return after error response to stop execution [OK]
Hint: Always return after sending error response to avoid double send [OK]
Common Mistakes:
  • Thinking length check direction is wrong
  • Confusing req.body with req.query
  • Believing res.send must be res.json
5. You want to manually validate a user registration form in Express. The form requires 'email' (non-empty string), 'password' (min 8 chars), and 'age' (optional, but if present must be number >= 13). Which code snippet correctly implements this validation?
hard
A. if (!req.body.email || req.body.email.length === 0) { return res.status(400).send('Email required'); } if (req.body.password.length < 8) { return res.status(200).send('Password too short'); } if (req.body.age && typeof req.body.age !== 'string') { return res.status(400).send('Age must be a string'); } next();
B. if (!req.body.email) { res.send('Email missing'); } if (req.body.password.length <= 8) { res.send('Password invalid'); } if (req.body.age < 13) { res.send('Too young'); } next();
C. if (req.body.email === '') { return res.status(500).send('Email error'); } if (req.body.password.length > 8) { return res.status(400).send('Password too short'); } if (req.body.age && req.body.age < 13) { return res.status(400).send('Age error'); } next();
D. if (!req.body.email || typeof req.body.email !== 'string') { return res.status(400).send('Email required'); } if (!req.body.password || req.body.password.length < 8) { return res.status(400).send('Password too short'); } if (req.body.age !== undefined && (typeof req.body.age !== 'number' || req.body.age < 13)) { return res.status(400).send('Age must be 13 or older'); } next();

Solution

  1. Step 1: Validate email presence and type

    if (!req.body.email || typeof req.body.email !== 'string') checks for missing, empty, or non-string email and returns 400 error if invalid.
  2. Step 2: Validate password length correctly

    if (!req.body.password || req.body.password.length < 8) checks for missing or short password (<8 chars) and returns 400 error.
  3. Step 3: Validate optional age correctly

    if (req.body.age !== undefined && (typeof req.body.age !== 'number' || req.body.age < 13)) checks if age provided, then ensures it's a number >=13, returns 400 if invalid.
  4. Final Answer:

    if (!req.body.email || typeof req.body.email !== 'string') { return res.status(400).send('Email required'); } if (!req.body.password || req.body.password.length < 8) { return res.status(400).send('Password too short'); } if (req.body.age !== undefined && (typeof req.body.age !== 'number' || req.body.age < 13)) { return res.status(400).send('Age must be 13 or older'); } next(); -> Option D
  5. Quick Check:

    All fields validated with correct conditions and error codes [OK]
Hint: Check each field with proper type and conditions, return on error [OK]
Common Mistakes:
  • Not returning after sending error response
  • Using wrong status codes like 200 or 500 for validation errors
  • Checking wrong types or missing optional field checks