Concept Flow - Validation with Joi
Define Joi Schema
Receive Input Data
Validate Data Against Schema
Proceed
This flow shows how Joi schema is defined, input data is validated, and based on validation result, either proceeds or returns an error.
import * as Joi from 'joi'; const schema = Joi.object({ name: Joi.string().min(1).required(), age: Joi.number().min(0) }); const result = schema.validate({ name: 'Alice', age: 25 });
| Step | Action | Input Data | Validation Result | Error Message |
|---|---|---|---|---|
| 1 | Define schema | N/A | Schema created | None |
| 2 | Validate input {name: 'Alice', age: 25} | {name: 'Alice', age: 25} | Valid | None |
| 3 | Validate input {name: '', age: -5} | {name: '', age: -5} | Invalid | "name" length must be at least 1 character long, "age" must be larger than or equal to 0 |
| 4 | Validate input {age: 30} | {age: 30} | Invalid | "name" is required |
| Variable | Start | After Step 2 | After Step 3 | After Step 4 |
|---|---|---|---|---|
| schema | undefined | Joi schema object | Joi schema object | Joi schema object |
| inputData | undefined | {name: 'Alice', age: 25} | {name: '', age: -5} | {age: 30} |
| validationResult | undefined | valid: true | valid: false | valid: false |
| errorMessage | undefined | none | "name" length must be at least 1 character long, "age" must be larger than or equal to 0 | "name" is required |
Joi Validation Quick Guide:
- Define schema with Joi.object({field: Joi.type().rules()})
- Use schema.validate(data) to check input
- Validation returns {value, error}
- Errors list all issues found
- Required fields must be present and valid
- Use in NestJS pipes for request validationJoi in a NestJS application?username?Joi.string()..required() ensures the field must be present and not empty.const schema = Joi.object({ age: Joi.number().min(18).required() });
const result = schema.validate({ age: 16 });result.error contain?age to be a number, at least 18, and required.age: 16, which is less than the minimum 18.result.error contains a message about age being too low.const schema = Joi.object({
email: Joi.string().email,
password: Joi.string().min(8).required()
});email method in Joi is a function and must be called with parentheses: email().Joi.string().email without parentheses, which is incorrect and will cause an error.name (required string), age (optional number, minimum 0), and email (required valid email). Which Joi schema correctly applies these rules?name is required string, age is number with min 0 (optional by default), email is required email string.Pass the test and this pattern moves unknown