Performance: Joi as validation alternative
This affects server response time and user experience by validating input efficiently before processing.
import Joi from 'joi'; const schema = Joi.object({ name: Joi.string().required(), age: Joi.number().min(0).required() }); app.post('/user', (req, res) => { const { error } = schema.validate(req.body); if (error) { return res.status(400).send(error.details[0].message); } res.send('User valid'); });
app.post('/user', (req, res) => { const { name, age } = req.body; if (!name || typeof name !== 'string') { return res.status(400).send('Invalid name'); } if (age === undefined || typeof age !== 'number' || age < 0) { return res.status(400).send('Invalid age'); } // proceed with processing res.send('User valid'); });
| Pattern | DOM Operations | Reflows | Paint Cost | Verdict |
|---|---|---|---|---|
| Manual validation with multiple if checks | 0 (server-side) | 0 | 0 | [!] OK but slower server response |
| Joi schema validation | 0 (server-side) | 0 | 0 | [OK] Faster and more reliable server validation |
Joi in an Express application?username?const schema = Joi.object({ age: Joi.number().min(18).required() });
const data = { age: 16 };
const result = schema.validate(data);result.error contain?const schema = Joi.object({ email: Joi.string().email() });
const data = { email: 12345 };
const result = schema.validate(data);name (string, required), age (optional number, min 0), and email (required valid email). Which Joi schema correctly enforces these rules?Pass the test and this pattern moves unknown