To validate an object against a schema in JavaScript or TypeScript, you can use a library like "Joi" or "Yup." These libraries allow you to define a schema that describes the expected shape of the object and then validate the object against that schema.

Here's how you can use "Joi" and "Yup" to validate an object:

Using Joi:

  1. Install the joi library:
bash
npm install joi
  1. Use Joi to define a schema and validate the object:
javascript
const Joi = require('joi'); // Define the schema const schema = Joi.object({ name: Joi.string().required(), age: Joi.number().integer().min(18).max(99), email: Joi.string().email(), }); // Object to validate const objToValidate = { name: 'John Doe', age: 25, email: 'john.doe@example.com', }; // Validate the object against the schema const { error, value } = schema.validate(objToValidate); if (error) { console.error('Validation error:', error.message); } else { console.log('Validated object:', value); }

Using Yup:

  1. Install the yup library:
bash
npm install yup
  1. Use Yup to define a schema and validate the object:
javascript
const yup = require('yup'); // Define the schema const schema = yup.object().shape({ name: yup.string().required(), age: yup.number().integer().min(18).max(99), email: yup.string().email(), }); // Object to validate const objToValidate = { name: 'John Doe', age: 25, email: 'john.doe@example.com', }; // Validate the object against the schema schema .validate(objToValidate) .then((validatedObject) => { console.log('Validated object:', validatedObject); }) .catch((error) => { console.error('Validation error:', error.message); });

In both cases, the validation will check whether the objToValidate object matches the schema's defined rules. If the object passes validation, the validated object will be returned. If there are validation errors, an error object will be returned, which contains information about the validation failure.

These libraries support more advanced schema rules, including nested objects, arrays, custom validation functions, and more. Refer to the documentation for each library to explore additional options and features.

Have questions or queries?
Get in Touch