joi


1. Basic Validation

const Joi = require('joi');

const schema = Joi.object().keys({
  name: Joi.string().required(),
  age: Joi.number().min(18).max(100),
});

const data = { name: 'John', age: 30 };

const { error, value } = schema.validate(data);

if (error) {
  console.log(error.message);
} else {
  console.log(value); // { name: 'John', age: 30 }
}

2. Nested Validation

const schema = Joi.object().keys({
  user: Joi.object().keys({
    name: Joi.string().required(),
    email: Joi.string().email().required(),
  }).required(),
  address: Joi.object().keys({
    street: Joi.string().required(),
    city: Joi.string().required(),
    state: Joi.string().length(2).required(),
  }).required(),
});

const data = {
  user: {
    name: 'John',
    email: 'john@example.com',
  },
  address: {
    street: '123 Main Street',
    city: 'Anytown',
    state: 'CA',
  },
};

const { error, value } = schema.validate(data);

if (error) {
  console.log(error.message);
} else {
  console.log(value); // { user: {...}, address: {...} }
}

3. Array Validation

4. Custom Error Messages

5. Custom Validation

6. Async Validation

7. Property Inclusion/Exclusion

8. Mutual Exclusion

9. Validating Alternative Types

10. Validating an Array with Specific Maximum or Minimum Length

11. Validating an Object with a Specific Number of Keys

12. Validating an Object with Specific Key Ordering

13. Validating an Object with a Specific Key Presence

14. Validating an Object with a Specific Key Absence

15. Validating an Object with Permitted Properties Only

16. Validating an Object with Conditional Properties

17. Validating an Object with Combined Conditions

18. Validating a File Upload

19. Validating a Nested Object

20. Validating a Property as a Function

21. Validating a Property as a Boolean

22. Validating a Property as a UUID

23. Validating a Property as an Array of Strings

24. Validating a Property as an Array of Objects

25. Validating a Property as a Date