Consider a NestJS controller method that uses Joi to validate incoming request data. If the data does not match the Joi schema, what will be the behavior?
import * as Joi from 'joi'; const schema = Joi.object({ username: Joi.string().min(3).required(), age: Joi.number().integer().min(18).required() }); // Assume this schema is used in a validation pipe in a controller method
Think about how NestJS validation pipes handle schema validation failures.
When Joi validation fails in a NestJS validation pipe, the framework automatically responds with a 400 Bad Request error and includes details about which fields failed validation.
Choose the Joi schema that correctly matches the requirements:
- email: optional, must be a valid email if present
- password: required, string, minimum length 8
Remember that by default fields are optional unless marked required.
Option B correctly sets email as optional (default) and password as required with minimum length 8. Option B requires email and password is optional. Option B is valid but redundant because Joi.string() is optional by default. Option B uses Joi.email() which is invalid syntax.
Examine the following Joi schema and identify the cause of the runtime error:
const schema = Joi.object({
name: Joi.string().min(3),
age: Joi.number().integer().min(0),
email: Joi.string().email().required(),
});Check the syntax of method calls on Joi validators.
The .required method must be called with parentheses as .required(). Without parentheses, it is a reference to the function, not a call, causing the schema to be invalid and throwing a runtime error.
Given the schema and input below, what is the value of result.error after validation?
const schema = Joi.object({
username: Joi.string().alphanum().min(3).max(10).required(),
password: Joi.string().pattern(new RegExp('^[a-zA-Z0-9]{3,30}$')).required()
});
const input = { username: 'ab', password: '123' };
const result = schema.validate(input);Check the username length and password pattern against the input.
The username 'ab' is only 2 characters, which is less than the minimum 3, so validation fails with an error about username length. The password '123' matches the pattern, so no error there.
Which statement best describes how Joi schemas are used within NestJS validation pipes to validate incoming requests?
Think about how validation pipes work and how Joi can be used in them.
Joi schemas are used in custom validation pipes in NestJS. The pipe runs Joi validation on the incoming data and throws exceptions if validation fails. This integrates with NestJS's exception handling system to send proper error responses.