Bird
Raised Fist0
Expressframework~10 mins

Validating body fields 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 - Validating body fields
Request received
Extract body fields
Check each required field
Field missing or invalid?
YesSend error response
No
All fields valid?
YesProcess request
No
Send error response
When a request arrives, the server extracts body fields, checks if required fields exist and are valid, then either sends an error or processes the request.
Execution Sample
Express
app.post('/user', (req, res) => {
  const { name, age } = req.body;
  if (!name || typeof name !== 'string') {
    return res.status(400).send('Name is required and must be a string');
  }
  res.send('User created');
});
This code checks if the 'name' field exists and is a string before creating a user.
Execution Table
StepActionBody FieldsCondition CheckedResultResponse Sent
1Request received{ name: 'Alice', age: 30 }Check if 'name' exists and is stringTrueNo
2All fields valid{ name: 'Alice', age: 30 }No missing or invalid fieldsTrueNo
3Process request{ name: 'Alice', age: 30 }N/AUser createdYes: 200 OK, 'User created'
4Request received{ age: 30 }Check if 'name' exists and is stringFalseNo
5Send error response{ age: 30 }Missing or invalid 'name'FalseYes: 400 Bad Request, 'Name is required and must be a string'
💡 Execution stops after sending response either success or error.
Variable Tracker
VariableStartAfter Step 1After Step 4Final
req.body{}{ name: 'Alice', age: 30 }{ age: 30 }N/A
nameundefined'Alice'undefinedN/A
ageundefined3030N/A
Key Moments - 2 Insights
Why does the server send an error if 'name' is missing or not a string?
Because the condition in step 1 or 4 fails, triggering the error response in step 5 as shown in the execution_table.
What happens if all required fields are valid?
The code proceeds to process the request and sends a success response as shown in step 3.
Visual Quiz - 3 Questions
Test your understanding
Look at the execution table, what is the response when 'name' is missing in the body?
A500 Internal Server Error
B200 OK with message 'User created'
C400 Bad Request with message 'Name is required and must be a string'
DNo response sent
💡 Hint
Check rows 4 and 5 in the execution_table where 'name' is missing.
At which step does the server confirm all fields are valid?
AStep 1
BStep 2
CStep 4
DStep 5
💡 Hint
Look at the 'All fields valid' action in the execution_table.
If the 'name' field was a number instead of a string, what would happen?
AThe server sends a 400 error response
BThe server sends a success response
CThe server ignores the 'name' field
DThe server crashes
💡 Hint
The condition checks type of 'name' as string in step 1 and 4.
Concept Snapshot
Validating body fields in Express:
- Extract fields from req.body
- Check required fields exist and types match
- If invalid, send 400 error response
- If valid, proceed with request
- Always respond to avoid hanging requests
Full Transcript
When Express receives a POST request, it extracts the body fields from req.body. The code checks if required fields like 'name' exist and are the correct type, for example a string. If the check fails, the server sends a 400 Bad Request response with an error message. If all fields are valid, the server processes the request and sends a success response. This flow ensures the server only accepts valid data and informs the client when data is missing or wrong.

Practice

(1/5)
1. What is the main reason to validate fields in req.body in an Express app?
easy
A. To log user data for analytics
B. To speed up the server response time
C. To change the data format automatically
D. To ensure the data received is complete and correct before processing

Solution

  1. Step 1: Understand the purpose of validation

    Validation checks if the data sent by the user is complete and correct.
  2. Step 2: Identify the benefit of validation

    It prevents errors and security issues by stopping bad data early.
  3. Final Answer:

    To ensure the data received is complete and correct before processing -> Option D
  4. Quick Check:

    Validation = Check data correctness [OK]
Hint: Validation means checking data before use [OK]
Common Mistakes:
  • Thinking validation speeds up server
  • Assuming validation changes data format
  • Confusing validation with logging
2. Which middleware is required to parse JSON body data in Express before validating fields?
easy
A. express.json()
B. express.static()
C. express.urlencoded()
D. express.raw()

Solution

  1. Step 1: Identify middleware for JSON parsing

    express.json() parses incoming JSON request bodies into JavaScript objects.
  2. Step 2: Compare with other middleware

    express.urlencoded() parses URL-encoded data, express.static() serves files, express.raw() parses raw buffer data.
  3. Final Answer:

    express.json() -> Option A
  4. Quick Check:

    JSON body parsing = express.json() [OK]
Hint: Use express.json() to parse JSON body data [OK]
Common Mistakes:
  • Using express.static() for body parsing
  • Confusing urlencoded with JSON parsing
  • Skipping middleware before validation
3. Given this Express route, what will be the response if req.body.name is missing?
app.post('/user', (req, res) => {
  if (!req.body.name) {
    return res.status(400).send('Name is required');
  }
  res.send(`Hello, ${req.body.name}`);
});
medium
A. Hello, undefined
B. Name is required
C. 500 Internal Server Error
D. Empty response

Solution

  1. Step 1: Check the condition for missing name

    The code checks if req.body.name is falsy (missing or empty).
  2. Step 2: Understand the response when name is missing

    If missing, it sends status 400 with message 'Name is required'.
  3. Final Answer:

    Name is required -> Option B
  4. Quick Check:

    Missing name triggers 400 error message [OK]
Hint: Missing field triggers error response [OK]
Common Mistakes:
  • Assuming undefined is sent as name
  • Expecting server error instead of 400
  • Thinking response is empty
4. What is wrong with this Express validation code?
app.post('/login', (req, res) => {
  if (req.body.username === undefined || req.body.password === undefined) {
    res.status(400).send('Missing fields');
  }
  res.send('Login success');
});
medium
A. It should check for null instead of undefined
B. It uses strict equality instead of loose equality
C. It does not stop execution after sending error response
D. It should use res.json() instead of res.send()

Solution

  1. Step 1: Analyze the error handling flow

    The code sends a 400 error but does not return or stop, so it continues to send success response.
  2. Step 2: Identify the fix

    Adding 'return' before res.status(400).send(...) stops further execution.
  3. Final Answer:

    It does not stop execution after sending error response -> Option C
  4. Quick Check:

    Missing return causes double response [OK]
Hint: Return after sending error to stop code [OK]
Common Mistakes:
  • Ignoring missing return after res.send()
  • Confusing equality checks with flow control
  • Thinking res.json() is required for errors
5. You want to validate that req.body.age is a number greater than 18 before processing. Which code snippet correctly validates this and sends a 400 error if invalid?
hard
A. if (!req.body.age || typeof req.body.age !== 'number' || req.body.age <= 18) { return res.status(400).send('Age must be a number over 18'); }
B. if (req.body.age <= 18) { res.status(400).send('Age must be over 18'); }
C. if (typeof req.body.age === 'string' && req.body.age > 18) { return res.status(400).send('Invalid age'); }
D. if (!req.body.age || req.body.age < 18) { res.send('Age is valid'); }

Solution

  1. Step 1: Check for presence and type of age

    Code verifies age exists and is a number using typeof.
  2. Step 2: Check age value is greater than 18

    It ensures age is over 18, else sends 400 error with message.
  3. Step 3: Confirm proper use of return to stop execution

    Return stops further processing after error response.
  4. Final Answer:

    if (!req.body.age || typeof req.body.age !== 'number' || req.body.age <= 18) { return res.status(400).send('Age must be a number over 18'); } -> Option A
  5. Quick Check:

    Check presence, type, and value with return [OK]
Hint: Check type and value, return on error [OK]
Common Mistakes:
  • Not checking type before comparing
  • Missing return after sending error
  • Sending success message on invalid data