Practice - 5 Tasks
Answer the questions below
1fill in blank
easyComplete the code to import the schema validation library.
Express
const Joi = require('[1]');
Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Using 'express' instead of 'joi'.
Trying to import 'mongoose' which is for databases.
✗ Incorrect
We use joi to define and validate schemas in Express apps.
2fill in blank
mediumComplete the code to define a schema for a user with a required string name.
Express
const schema = Joi.object({ name: Joi.[1]().required() }); Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Using number() for a name.
Using array() which is for lists.
✗ Incorrect
The string() method defines a string type in Joi schemas.
3fill in blank
hardFix the error in the validation call to check the request body.
Express
const { error } = schema.[1](req.body); Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Using non-existent methods like validateBody or check.
Confusing with test which is not a Joi method.
✗ Incorrect
The correct method to validate data with Joi is validate().
4fill in blank
hardFill both blanks to create middleware that validates the request body and sends an error if invalid.
Express
function validateUser(req, res, next) {
const { error } = schema.[1](req.body);
if (error) return res.status([2]).send(error.details[0].message);
next();
} Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Using status 500 which means server error, not client error.
Using a wrong method like 'check' instead of 'validate'.
✗ Incorrect
Use validate to check the data and send status 400 for bad requests.
5fill in blank
hardFill all three blanks to define a schema with a required string 'username', an optional number 'age', and validate an object.
Express
const schema = Joi.object({
username: Joi.[1]().required(),
age: Joi.[2](),
});
const { error } = schema.[3]({ username: 'Alice', age: 30 }); Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Mixing up data types like using boolean for age.
Forgetting to call 'validate' to check the data.
✗ Incorrect
Use string() for username, number() for age, and validate() to check the object.