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 validation