Performance: Custom validation rules
Custom validation rules affect server response time and user experience by adding processing before sending responses.
Jump into concepts and practice - no test required
const validateInput = (req, res, next) => {
const { email, password } = req.body;
if (!email || !email.includes('@')) {
return res.status(400).send('Invalid email');
}
if (!password || password.length < 8) {
return res.status(400).send('Password too short');
}
next();
};
app.post('/submit', validateInput, (req, res) => {
res.send('Success');
});app.post('/submit', (req, res) => { if (!req.body.email || !req.body.email.includes('@')) { res.status(400).send('Invalid email'); return; } if (!req.body.password || req.body.password.length < 8) { res.status(400).send('Password too short'); return; } // more validations inline res.send('Success'); });
| Pattern | Server Processing | Blocking Time | Response Delay | Verdict |
|---|---|---|---|---|
| Inline validation in route handler | High (sequential checks) | Blocks event loop | Adds 50-100ms delay | [X] Bad |
| Validation middleware with early exit | Low (focused checks) | Non-blocking after failure | Minimal delay | [OK] Good |
custom() in Express validation?custom()custom() method allows you to write your own validation logic beyond built-in checks.custom() should throw an error if validation fails and return true if it passes.req.body.username is "abc"?
check('username').custom(value => {
if(value.length < 5) throw new Error('Too short');
return true;
})check('email').custom(value => {
if(!value.includes('@'))
return new Error('Invalid email');
return true;
})new Error('Invalid email') instead of throwing it, so validation will not fail as expected.