Bird
Raised Fist0
Expressframework~10 mins

Schema validation 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 - Schema validation
Receive HTTP Request
Extract Data from Request
Validate Data Against Schema
Proceed
Next Middleware
The server receives a request, extracts data, checks it against rules (schema), then either continues or sends an error.
Execution Sample
Express
const schema = Joi.object({ name: Joi.string().required() });
app.post('/user', (req, res) => {
  const { error } = schema.validate(req.body);
  if (error) return res.status(400).send(error.message);
  res.send('User valid');
});
This code checks if the request body has a 'name' string; if not, it sends an error, else confirms validity.
Execution Table
StepActionInput DataValidation ResultResponse Sent
1Receive POST /user{ name: 'Alice' }ValidNo
2Validate data{ name: 'Alice' }No errorNo
3Send success response'User valid'
4Receive POST /user{ name: 123 }InvalidNo
5Validate data{ name: 123 }Error: 'name' must be a stringNo
6Send error response400 Bad Request with error message
💡 Stops when data is invalid or after sending success response
Variable Tracker
VariableStartAfter Step 2 (Valid)After Step 5 (Invalid)
req.body{}{ name: 'Alice' }{ name: 123 }
errorundefinedundefined"'name' must be a string"
response status200 (default)200400
response message'''User valid'"'name' must be a string"
Key Moments - 2 Insights
Why does the server send a 400 error when the name is a number?
Because the schema requires 'name' to be a string. The validation fails at step 5 in the execution_table, triggering the error response.
What happens if the request body is missing the 'name' field?
The validation will fail since 'name' is required. This is similar to step 5 where an error is returned and the server sends a 400 response.
Visual Quiz - 3 Questions
Test your understanding
Look at the execution_table, what is the validation result at step 2?
AMissing required field
BError: 'name' must be a string
CNo error
DValidation not performed
💡 Hint
Check the 'Validation Result' column at step 2 in the execution_table
At which step does the server send a 400 Bad Request response?
AStep 6
BStep 3
CStep 4
DStep 1
💡 Hint
Look at the 'Response Sent' column for the 400 error in the execution_table
If the schema required an additional 'age' number field, how would the validation result change for input { name: 'Alice' }?
AValidation passes as before
BValidation fails due to missing 'age'
CValidation error on 'name'
DServer crashes
💡 Hint
Consider the schema rules and how missing required fields affect validation in the execution_table
Concept Snapshot
Schema validation in Express:
- Define a schema with rules (e.g., using Joi)
- On request, validate input data against schema
- If valid, proceed to next step
- If invalid, send error response (e.g., 400 Bad Request)
- Helps ensure data correctness before processing
Full Transcript
Schema validation in Express means checking incoming request data against a set of rules called a schema. When the server gets a request, it extracts the data and compares it to the schema. If the data matches the rules, the server continues processing. If not, it sends back an error message and stops. For example, if the schema says 'name' must be a string, and the request sends a number instead, the server will respond with a 400 error. This process helps keep the app safe and working correctly by catching bad data early.

Practice

(1/5)
1. What is the main purpose of schema validation in an Express app?
easy
A. To store data permanently in the database
B. To speed up the server response time
C. To style the user interface automatically
D. To check if incoming data matches expected rules before processing

Solution

  1. Step 1: Understand schema validation role

    Schema validation ensures data received matches rules like type and format.
  2. Step 2: Identify main purpose in Express

    It prevents bad data from causing errors or security issues by checking before use.
  3. Final Answer:

    To check if incoming data matches expected rules before processing -> Option D
  4. Quick Check:

    Schema validation = data check before use [OK]
Hint: Schema validation means checking data fits rules before use [OK]
Common Mistakes:
  • Thinking validation speeds up server
  • Confusing validation with UI styling
  • Assuming validation stores data
2. Which of the following is the correct way to define a Joi schema for a required string named username?
easy
A. const schema = Joi.object({ username: Joi.string().required() });
B. const schema = Joi.string().required();
C. const schema = Joi.string().optional();
D. const schema = Joi.number().required();

Solution

  1. Step 1: Recall Joi schema structure for objects

    Joi schemas for objects use Joi.object({ key: rule }) format.
  2. Step 2: Check correct rule for required string property

    Property username must be a string and required, so use Joi.string().required().
  3. Final Answer:

    const schema = Joi.object({ username: Joi.string().required() }); -> Option A
  4. Quick Check:

    Object schema with required string property = const schema = Joi.object({ username: Joi.string().required() }); [OK]
Hint: Use Joi.object({ key: Joi.type().required() }) for required fields [OK]
Common Mistakes:
  • Defining schema as Joi.string() alone for object data
  • Using optional() instead of required()
  • Using wrong data type like Joi.number() for string
3. Given this Joi schema and data, what will schema.validate(data) return?
const schema = Joi.object({ age: Joi.number().min(18).required() });
const data = { age: 16 };
medium
A. Validation fails because age is less than 18
B. Validation passes with value { age: 16 }
C. Validation fails because age is missing
D. Validation passes with value { age: 18 }

Solution

  1. Step 1: Analyze schema rules for age

    Age must be a number, minimum 18, and required.
  2. Step 2: Check data against schema

    Data has age 16, which is less than minimum 18, so validation fails.
  3. Final Answer:

    Validation fails because age is less than 18 -> Option A
  4. Quick Check:

    Age < 18 fails min rule = Validation fails because age is less than 18 [OK]
Hint: Check min/max rules carefully when validating numbers [OK]
Common Mistakes:
  • Assuming 16 passes min(18) rule
  • Confusing missing field with invalid value
  • Thinking Joi changes value automatically
4. What is wrong with this Express route using Joi validation?
app.post('/user', (req, res) => {
  const schema = Joi.object({ email: Joi.string().email().required() });
  const result = schema.validate(req.body.email);
  if (result.error) {
    res.status(400).send('Invalid email');
  } else {
    res.send('User created');
  }
});
medium
A. It does not call next() after validation
B. It validates only the email string, not the whole object
C. It uses res.send instead of res.json
D. It should use Joi.number() for email

Solution

  1. Step 1: Check what is validated

    The schema expects an object with an email property, but code validates req.body.email (a string).
  2. Step 2: Understand Joi object validation

    To validate the whole object, pass req.body to schema.validate, not just one property.
  3. Final Answer:

    It validates only the email string, not the whole object -> Option B
  4. Quick Check:

    Validate whole object, not single property [OK]
Hint: Validate req.body object, not a single field string [OK]
Common Mistakes:
  • Validating only a property instead of full object
  • Confusing res.send and res.json (both work)
  • Forgetting to call next() is not required here
  • Using wrong Joi type for email
5. You want to validate a user object with optional phone that must be a string of 10 digits if present, and a required name string. Which Joi schema correctly enforces this?
hard
A. Joi.object({ name: Joi.string().required(), phone: Joi.string().pattern(/\d+/).required() })
B. Joi.object({ name: Joi.string(), phone: Joi.number().length(10).optional() })
C. Joi.object({ name: Joi.string().required(), phone: Joi.string().pattern(/^\d{10}$/).optional() })
D. Joi.object({ name: Joi.string().required(), phone: Joi.string().length(10).required() })

Solution

  1. Step 1: Identify required and optional fields

    Name is required string; phone is optional string matching exactly 10 digits.
  2. Step 2: Check regex pattern and optional usage

    Pattern /^\d{10}$/ matches exactly 10 digits; phone is optional, so use .optional().
  3. Step 3: Eliminate incorrect options

    Other options make phone required, use wrong types like Joi.number(), apply invalid methods like .length(10) on numbers, or use loose patterns like /\d+/.
  4. Final Answer:

    Joi.object({ name: Joi.string().required(), phone: Joi.string().pattern(/^\d{10}$/).optional() }) -> Option C
  5. Quick Check:

    Required name + optional 10-digit phone pattern = Joi.object({ name: Joi.string().required(), phone: Joi.string().pattern(/^\d{10}$/).optional() }) [OK]
Hint: Use .pattern(/^\d{10}$/) for exact 10-digit string [OK]
Common Mistakes:
  • Using Joi.number() for phone instead of string
  • Making optional field required
  • Using .length(10) on string without pattern
  • Using loose regex that allows wrong formats