0
0
Expressframework~10 mins

Custom validation rules in Express - Step-by-Step Execution

Choose your learning style9 modes available
Concept Flow - Custom validation rules
Receive request data
Apply built-in validations
Apply custom validation function
Is data valid?
NoSend error response
Yes
Proceed to next middleware or handler
The flow shows how Express receives data, applies built-in and custom validations, then either sends errors or continues processing.
Execution Sample
Express
const { body, validationResult } = require('express-validator');

app.post('/user', [
  body('age').custom(value => {
    if (value < 18) throw new Error('Must be 18 or older');
    return true;
  })
], (req, res) => {
  const errors = validationResult(req);
  if (!errors.isEmpty()) return res.status(400).json({ errors: errors.array() });
  res.send('User valid');
});
This code adds a custom validation to check if age is 18 or older, then sends errors or success.
Execution Table
StepActionInput ValueValidation ResultNext Step
1Receive request with age=1616Not validated yetApply built-in validations
2Apply built-in validations16Pass (no built-in rules here)Apply custom validation
3Run custom validation function16Fail: 'Must be 18 or older'Send error response
4Send error responseN/AResponse 400 with error messageEnd
5Receive request with age=2020Not validated yetApply built-in validations
6Apply built-in validations20PassApply custom validation
7Run custom validation function20PassProceed to handler
8Send success responseN/AResponse 200 'User valid'End
💡 Execution stops after sending response: either error if validation fails or success if passes.
Variable Tracker
VariableStartAfter Step 3 (age=16)After Step 7 (age=20)Final
ageundefined162020 or 16 depending on request
validationResult.errorsempty[{msg:'Must be 18 or older'}]emptyErrors or empty array
response.statusunset400200Final HTTP status code
response.bodyunset{"errors":[{"msg":"Must be 18 or older"}]}"User valid"Final response content
Key Moments - 3 Insights
Why does the custom validation function throw an error instead of returning false?
Throwing an Error inside the custom validator signals express-validator that validation failed with a message. Returning false would not provide the error message. See execution_table row 3.
What happens if validationResult finds errors?
If errors exist, the code sends a 400 response with error details and stops further processing. See execution_table row 4.
Can custom validation access other request fields?
Yes, the custom validator can access req object if needed, but here it only checks the value directly. This is common for cross-field checks.
Visual Quiz - 3 Questions
Test your understanding
Look at the execution table, what validation result occurs at step 3 when age is 16?
AFail with message 'Must be 18 or older'
BPass
CNo validation performed
DThrows a system error
💡 Hint
Check the 'Validation Result' column in row 3 of the execution_table.
At which step does the server send a success response for age 20?
AStep 4
BStep 8
CStep 6
DStep 7
💡 Hint
Look for 'Send success response' action in the execution_table.
If the custom validator returned false instead of throwing an error, what would happen?
AValidation would fail with the same error message
BValidation would pass silently
CValidation would fail but no error message would be shown
DServer would crash
💡 Hint
Recall key_moments explanation about throwing Error vs returning false.
Concept Snapshot
Custom validation rules in Express use functions that throw errors to signal validation failure.
Use express-validator's body().custom() to add these rules.
If validation fails, send error response with details.
If passes, continue to next middleware or handler.
This allows flexible checks beyond built-in validators.
Full Transcript
This visual execution trace shows how Express handles custom validation rules using express-validator. First, the server receives request data. Built-in validations run, then custom validation functions check specific conditions. If the custom validator throws an error, validation fails and the server sends a 400 error response with messages. If validation passes, the server proceeds to handle the request normally and sends a success response. Variables like age, validation errors, and response status update step-by-step. Key moments clarify why throwing errors is needed for validation failure and how errors stop request processing. The quiz tests understanding of validation results and response steps. This helps beginners see exactly how custom validation works in Express.