const Joi = require('joi'); const schema = Joi.object({ name: Joi.string().min(3).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 created'); });
When Joi validation fails, the error object contains details about the failure. The code sends a 400 status with the first error message to inform the client about the invalid input.
email (required, valid email) and age (optional, integer, minimum 18). Which Joi schema is correct?Option D uses the correct Joi methods in the right order: Joi.string().email().required() for email and Joi.number().integer().min(18) for age. Other options misuse method order or constraints.
const schema = Joi.object({ username: Joi.string().min(1) });
const result = schema.validate({ username: '' });
console.log(result.error);Joi.string() allows empty strings unless you explicitly forbid them with .required() or .empty(). The .min(1) method checks length but empty strings are allowed unless forbidden.
validatedData after validation?const schema = Joi.object({ name: Joi.string().trim().required(), age: Joi.number().default(30) });
const input = { name: ' Alice ' };
const { value: validatedData } = schema.validate(input);
console.log(validatedData);The trim() method removes spaces around the string, so name becomes 'Alice'. The age field is missing in input, so Joi adds the default value 30.
Joi lets you define clear, reusable validation rules that help catch errors early and keep code clean. It does not fix inputs automatically or remove the need for error handling. Performance depends on use case.