Discover how custom validation rules save you from endless, error-prone input checks!
Why Custom validation rules in Express? - Purpose & Use Cases
Start learning this pattern below
Jump into concepts and practice - no test required
Imagine building a web form where users enter their data, and you have to check every input manually in your code.
You write many if-else checks for each field, like checking if an email looks right or if a password is strong enough.
Manually checking each input is slow and messy.
It's easy to forget a rule or make mistakes, causing bugs or security holes.
Also, repeating similar checks everywhere makes your code hard to read and maintain.
Custom validation rules let you define clear, reusable checks for your data.
Express middleware or libraries can run these rules automatically before your main code runs.
This keeps your code clean, consistent, and easy to update.
if (!email.includes('@')) { return error; } if (password.length < 8) { return error; }
app.post('/signup', validateEmail(), validatePassword(), (req, res) => { /* handle signup */ });You can build reliable, secure forms that automatically check user input with less code and fewer mistakes.
When signing up on a website, custom validation rules ensure your email and password meet requirements before creating your account.
Manual input checks are slow and error-prone.
Custom validation rules make checks reusable and automatic.
This leads to cleaner, safer, and easier-to-maintain code.
Practice
custom() in Express validation?Solution
Step 1: Understand the role of
Thecustom()custom()method allows you to write your own validation logic beyond built-in checks.Step 2: Identify the purpose in input validation
It is used to check inputs with rules you define, like checking a password strength or a special format.Final Answer:
To create your own rules for checking input values -> Option DQuick Check:
Custom validation = custom rules [OK]
- Thinking custom() sanitizes inputs automatically
- Confusing custom() with response formatting
- Assuming custom() connects to databases
Solution
Step 1: Review correct custom validation syntax
The function insidecustom()should throw an error if validation fails and return true if it passes.Step 2: Analyze each option
check('age').custom(value => { if(value < 18) throw new Error('Too young'); return true; }) throws an error when value is less than 18 and returns true otherwise, which is correct. check('age').custom(value => value < 18 ? true : false) returns true when value is less than 18, which is opposite logic. check('age').custom(value => { return false; }) always returns false, which fails validation. check('age').custom(value => { throw 'Error'; }) throws an error unconditionally, so it always fails.Final Answer:
check('age').custom(value => { if(value < 18) throw new Error('Too young'); return true; }) -> Option AQuick Check:
Throw error on fail, return true on pass [OK]
- Returning false instead of throwing error
- Throwing error without condition
- Returning true on invalid input
req.body.username is "abc"?
check('username').custom(value => {
if(value.length < 5) throw new Error('Too short');
return true;
})Solution
Step 1: Check the input value length
The input "abc" has length 3, which is less than 5.Step 2: Apply the custom validation logic
The function throws an error 'Too short' if length is less than 5, so it throws an error here causing validation to fail.Final Answer:
Validation fails with 'Too short' error -> Option AQuick Check:
Input too short = error thrown [OK]
- Assuming validation passes for short input
- Confusing error throwing with warnings
- Expecting syntax errors from valid code
check('email').custom(value => {
if(!value.includes('@'))
return new Error('Invalid email');
return true;
})Solution
Step 1: Understand error signaling in custom validation
Custom validators must throw an error to indicate failure, not return an Error object.Step 2: Analyze the given code
The code returnsnew Error('Invalid email')instead of throwing it, so validation will not fail as expected.Final Answer:
It should throw an error, not return it -> Option CQuick Check:
Throw error to fail validation [OK]
- Returning Error object instead of throwing
- Checking wrong condition for email
- Returning false instead of throwing error
Solution
Step 1: Check each condition with proper error throwing
check('password').custom(value => { if(!/[A-Z]/.test(value)) throw new Error('Missing uppercase'); if(!/\d/.test(value)) throw new Error('Missing number'); if(value.length < 8) throw new Error('Too short'); return true; }) checks each condition separately and throws a specific error if it fails, returning true only if all pass.Step 2: Compare other options for correctness
check('password').custom(value => { if(value.length < 8) return false; if(!/[A-Z]/.test(value)) return false; if(!/\d/.test(value)) return false; return true; }) returns false instead of throwing errors, which is incorrect. check('password').custom(value => { if(value.length < 8) throw 'Too short'; if(!/[A-Z]/.test(value)) throw 'Missing uppercase'; if(!/\d/.test(value)) throw 'Missing number'; return false; }) throws string errors and returns false at the end, which breaks the rule of returning true on success. check('password').custom(value => { if(value.length >= 8 && /[A-Z]/.test(value) && /\d/.test(value)) return true; else return false; }) returns false instead of throwing an error if conditions fail, which is incorrect.Final Answer:
check('password').custom(value => { if(!/[A-Z]/.test(value)) throw new Error('Missing uppercase'); if(!/\d/.test(value)) throw new Error('Missing number'); if(value.length < 8) throw new Error('Too short'); return true; }) -> Option BQuick Check:
Throw specific errors, return true if all pass [OK]
- Returning false instead of throwing errors
- Throwing strings instead of Error objects
- Returning false on success
