The most common schema used in JavaScript is JSON Schema (json-schema.org). To use it, you first define a schema written in JSON, and then use a schema validation library to compare the object of interest with the schema to see if they match.
But before we explain the syntax of JSON Schema, let's take a look at two major JavaScript libraries that support schema validation while not using JSON Schema:
- joi (https://github.com/hapijs/joi) allows you to define requirements in a composable, chainable manner, which means that the code is very readable. It has over 9,000 stars on GitHub and is depended on by over 94,000 repositories and 3,300 packages:
const schema = Joi.object().keys({
username: Joi.string().alphanum().min(3).max(30).required(),
password: Joi.string().regex(/^[a-zA-Z0-9]{3,30}$/),
access_token: [Joi.string(), Joi.number()],
birthyear: Joi.number().integer().min(1900).max(2013),
email: Joi.string().email()
}).with('username', 'birthyear').without('password', 'access_token');
const result = Joi.validate({ username: 'abc', birthyear: 1994 }, schema);
- validate.js (https://validatejs.org/) is another very expressive validation library, and allows you to define your own custom validation function. It has 1,700 stars on GitHub, and is depended on by over 2,700 repositories and 290 packages:
var constraints = {
username: {
presence: true,
exclusion: {
within: ["nicklas"],
message: "'%{value}' is not allowed"
}
},
password: {
presence: true,
length: {
minimum: 6,
message: "must be at least 6 characters"
}
}
};
validate({password: "bad"}, constraints);