0
0
Expressframework~10 mins

Schema validation in Express - Interactive Code Practice

Choose your learning style9 modes available
Practice - 5 Tasks
Answer the questions below
1fill in blank
easy

Complete the code to import the schema validation library.

Express
const Joi = require('[1]');
Drag options to blanks, or click blank then click option'
Abody-parser
Bexpress
Cmongoose
Djoi
Attempts:
3 left
💡 Hint
Common Mistakes
Using 'express' instead of 'joi'.
Trying to import 'mongoose' which is for databases.
2fill in blank
medium

Complete 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'
Astring
Bnumber
Cboolean
Darray
Attempts:
3 left
💡 Hint
Common Mistakes
Using number() for a name.
Using array() which is for lists.
3fill in blank
hard

Fix 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'
Avalidate
Btest
Ccheck
DvalidateBody
Attempts:
3 left
💡 Hint
Common Mistakes
Using non-existent methods like validateBody or check.
Confusing with test which is not a Joi method.
4fill in blank
hard

Fill 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'
Avalidate
B400
C500
Dcheck
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'.
5fill in blank
hard

Fill 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'
Astring
Bnumber
Cvalidate
Dboolean
Attempts:
3 left
💡 Hint
Common Mistakes
Mixing up data types like using boolean for age.
Forgetting to call 'validate' to check the data.