What is @humanwhocodes/object-schema?
The @humanwhocodes/object-schema package is a utility for validating JavaScript objects against a predefined schema. It allows developers to ensure that objects match a specific structure, types, and constraints, making it easier to enforce data integrity throughout applications.
What are @humanwhocodes/object-schema's main functionalities?
Type Validation
This feature allows for the validation of object properties against specified types. In the example, the schema is defined to expect a property 'name' of type string. The validate method then checks if the provided object matches this schema.
{"const schema = new Schema({name: Schema.string()}); const result = schema.validate({name: 'John Doe'}); if (result.valid) { console.log('Valid!'); } else { console.log('Invalid:', result.errors); }"}
Required Properties
This feature ensures that certain properties are present in the object being validated. In the code sample, the 'name' property is marked as required, and the validation will fail if it is missing.
{"const schema = new Schema({name: Schema.string().required()}); const result = schema.validate({}); if (result.valid) { console.log('Valid!'); } else { console.log('Invalid:', result.errors); }"}
Default Values
This feature allows specifying default values for properties that are not present in the validated object. In the example, if the 'age' property is missing, it will default to 18.
{"const schema = new Schema({age: Schema.number().default(18)}); const result = schema.validate({}); console.log(result.value); // { age: 18 }"}
Other packages similar to @humanwhocodes/object-schema
joi
Joi is a powerful schema description language and data validator for JavaScript. Compared to @humanwhocodes/object-schema, Joi offers a more extensive set of features for describing and validating data structures, making it suitable for more complex validation scenarios.
yup
Yup is a JavaScript schema builder for value parsing and validation. It adopts a similar approach to @humanwhocodes/object-schema but provides a more fluent interface and additional methods for transforming values, making it a good choice for both client-side and server-side validation.
ajv
Ajv is a fast JSON schema validator. It supports the latest JSON Schema standards and is known for its performance. Compared to @humanwhocodes/object-schema, Ajv is more focused on validating JSON data structures according to the JSON Schema standard, offering a different approach to schema validation.
JavaScript ObjectSchema Package
by Nicholas C. Zakas
If you find this useful, please consider supporting my work with a donation.
Overview
A JavaScript object merge/validation utility where you can define a different merge and validation strategy for each key. This is helpful when you need to validate complex data structures and then merge them in a way that is more complex than Object.assign()
.
Installation
You can install using either npm:
npm install @humanwhocodes/object-schema
Or Yarn:
yarn add @humanwhocodes/object-schema
Usage
Use CommonJS to get access to the ObjectSchema
constructor:
const { ObjectSchema } = require("@humanwhocodes/object-schema");
const schema = new ObjectSchema();
schema.defineStrategies([
{
name: "downloads",
required: true,
merge(value1, value2) {
return value1 + value2;
},
validate(value) {
if (typeof value !== "number") {
throw new Error("Expected downloads to be a number.");
}
}
},
{
name: "versions",
required: true,
merge(value1, value2) {
return value1.concat(value2);
},
validate(value) {
if (!Array.isArray(value)) {
throw new Error("Expected versions to be an array.");
}
}
}
]);
const record1 = {
downloads: 25,
versions: [
"v1.0.0",
"v1.1.0",
"v1.2.0"
]
};
const record2 = {
downloads: 125,
versions: [
"v2.0.0",
"v2.1.0",
"v3.0.0"
]
};
schema.validate(record1);
schema.validate(record2);
const result = schema.merge(record1, record2);
const result = {
downloads: 75,
versions: [
"v1.0.0",
"v1.1.0",
"v1.2.0",
"v2.0.0",
"v2.1.0",
"v3.0.0"
]
};
Tips and Tricks
Remove Keys During Merge
If the merge strategy for a key returns undefined
, then the key will not appear in the final object. For example:
const schema = new ObjectSchema();
schema.defineStrategy({
name: "date",
merge() {
return undefined;
},
validate(value) {
Date.parse(value);
}
})
const object1 = { date: "5/5/2005" };
const object2 = { date: "6/6/2006" };
const result = schema.merge(object1, object2);
console.log("date" in result);
Requiring Another Key Be Present
If you'd like the presence of one key to require the presence of another key, you can use the requires
property to specify an array of other properties that any key requires. For example:
const schema = new ObjectSchema();
schema.defineStrategies([
{
name: "date",
merge() {
return undefined;
},
validate(value) {
Date.parse(value);
}
},
{
name: "time",
requires: ["date"],
merge(first, second) {
return second;
},
validate(value) {
}
}
]);
schema.validate({
time: "13:45"
});
In this example, even though date
is an optional key, it is required to be present whenever time
is present.
License
BSD 3-Clause