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:
- Install the
joi
library:
bashnpm install joi
- Use Joi to define a schema and validate the object:
javascriptconst 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:
- Install the
yup
library:
bashnpm install yup
- Use Yup to define a schema and validate the object:
javascriptconst 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.