README
simple-schema
SimpleSchema validates JavaScript objects to ensure they match a schema. It can also clean the objects to automatically convert types, remove unsupported properties, and add automatic values such that the object is then more likely to pass validation.
There are a lot of similar packages for validating objects. These are some of the features of this package that might be good reasons to choose this one over another:
- Isomorphic. Works in NodeJS and modern browsers.
- The object you validate can be a MongoDB modifier. SimpleSchema understands how to properly validate it such that the object in the database, after undergoing modification, will be valid.
- Optional Tracker reactivity for Meteor apps
- Powerful customizable error message system with decent English language defaults and support for localization, which makes it easy to drop this package in and display the validation error messages to end users.
- Recommended by MDG, the group that makes Meteor
- Has hundreds of tests and is used in production apps of various sizes
- Used by the Collection2 and AutoForm Meteor packages.
There are also reasons not to choose this package. Because of all it does, this package is more complex than (but still "simple" :) ) and slower than some other packages. Based on your needs, you should decide whether these tradeoffs are acceptable. One faster but less powerful option is simplecheck.
Table of Contents generated with DocToc
- simple-schema
- The History of SimpleSchema
- Installation
- Lingo
- Quick Start
- Defining a Schema
- Schema Keys
- Schema Rules
- Validating Data
- The Object to Validate
- Ways to Perform Validation
- Validating an Object
- Validating Only Some Keys in an Object
- Validation Options
- Validating and Throwing ValidationErrors
- Custom Field Validation
- Custom Whole-Document Validators
- Manually Adding a Validation Error
- Asynchronous Custom Validation on the Client
- Getting a List of Invalid Keys and Validation Error Messages
- Customizing Validation Messages
- Other Validation Context Methods
- Other SimpleSchema Methods
- Cleaning Objects
- Dates
- Best Practice Code Examples
- Debug Mode
- Extending the Schema Options
- Add On Packages
- License
- Contributing
The History of SimpleSchema
SimpleSchema was first released as a Meteor package in mid-2013. Version 1.0 was released in September 2014. In mid-2016, version 2.0 was released as an NPM package, which can be used in Meteor, NodeJS, or static browser apps.
If you are migrating from the Meteor package, refer to the CHANGELOG
Installation
npm install @clayne/simple-schema
There are other NPM packages named simpleschema
and simple-schema
. Make sure you install the right package. There is no "e" on "simpl".
Lingo
In this documentation:
- "key", "field", and "property" generally all mean the same thing: an identifier for some part of an object that is validated by your schema. SimpleSchema uses dot notation to identify nested keys.
- "validate" means to check whether an object matches what you expect, for example, having the expected keys with the expected data types, expected string lengths, etc.
Quick Start
Validate an Object and Throw an Error
import SimpleSchema from '@clayne/simple-schema';
new SimpleSchema({
name: String,
}).validate({
name: 2,
});
Validate an Array of Objects and Throw an Error
An error is thrown for the first invalid object found.
import SimpleSchema from '@clayne/simple-schema';
new SimpleSchema({
name: String,
}).validate([
{ name: 'Bill' },
{ name: 2 },
]);
Validate an Object and Get the Errors
import SimpleSchema from '@clayne/simple-schema';
const validationContext = new SimpleSchema({
name: String,
}).newContext();
validationContext.validate({
name: 2,
});
console.log(validationContext.isValid());
console.log(validationContext.validationErrors());
Validate a MongoDB Modifier
import SimpleSchema from '@clayne/simple-schema';
const validationContext = new SimpleSchema({
name: String,
}).newContext();
validationContext.validate({
$set: {
name: 2,
},
}, { modifier: true });
console.log(validationContext.isValid());
console.log(validationContext.validationErrors());
Enable Meteor Tracker Reactivity
import SimpleSchema from '@clayne/simple-schema';
import { Tracker } from 'meteor/tracker';
const validationContext = new SimpleSchema({
name: String,
}, { tracker: Tracker }).newContext();
Tracker.autorun(function () {
console.log(validationContext.isValid());
console.log(validationContext.validationErrors());
});
validationContext.validate({
name: 2,
});
validationContext.validate({
name: 'Joe',
});
Automatically Clean the Object Before Validating It
TO DO
Set Default Cleaning Options
import SimpleSchema from '@clayne/simple-schema';
const mySchema = new SimpleSchema({
name: String,
}, {
clean: {
filter: true,
autoConvert: true,
removeEmptyStrings: true,
trimStrings: true,
getAutoValues: true,
removeNullsFromArrays: true,
},
});
Explicitly Clean an Object
import SimpleSchema from '@clayne/simple-schema';
const mySchema = new SimpleSchema({ name: String });
const doc = { name: 123 };
const cleanDoc = mySchema.clean(doc);
// cleanDoc is now mutated to hopefully have a better chance of passing validation
console.log(typeof cleanDoc.name); // string
Works for a MongoDB modifier, too:
import SimpleSchema from '@clayne/simple-schema';
const mySchema = new SimpleSchema({ name: String });
const modifier = { $set: { name: 123 } };
const cleanModifier = mySchema.clean(modifier);
// doc is now mutated to hopefully have a better chance of passing validation
console.log(typeof cleanModifier.$set.name); // string
Defining a Schema
Let's get into some more details about the different syntaxes that are supported when defining a schema. It's probably best to start with the simplest syntax. Here's an example:
Shorthand Definitions
import SimpleSchema from '@clayne/simple-schema';
const schema = new SimpleSchema({
name: String,
age: SimpleSchema.Integer,
registered: Boolean,
});
This is referred to as "shorthand" syntax. You simply map a property name to a type. When validating, SimpleSchema will make sure that all of those properties are present and are set to a value of that type.
Longhand Definitions
In many cases, you will need to use longhand in order to define additional rules beyond what the data type should be.
import SimpleSchema from '@clayne/simple-schema';
const schema = new SimpleSchema({
name: {
type: String,
max: 40,
},
age: {
type: SimpleSchema.Integer,
optional: true,
},
registered: {
type: Boolean,
defaultValue: false,
},
});
Mixing Shorthand with Longhand
You can use any combination of shorthand and longhand:
import SimpleSchema from '@clayne/simple-schema';
const schema = new SimpleSchema({
name: String,
age: {
type: SimpleSchema.Integer,
optional: true,
},
registered: Boolean,
});
More Shorthand
If you set the schema key to a regular expression, then the type
will be String
and the string must match the provided regular expression.
For example, this:
{
exp: /foo/
}
is equivalent to:
{
exp: { type: String, regEx: /foo/ }
}
You can also set the schema key to an array of some type:
{
friends: [String],
}
is equivalent to:
{
friends: { type: Array },
'friends.