Meteor SimpleSchema
Attention! 🧐
This package is back under maintenance by the Meteor Community Packages group 🚀 Consider this a hard-fork to ensure a future-proof maintenance with focus on Meteor-Compatibility (Meteor 2.x; 3.x and beyond)! ☄️
About this package
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 on Server and Client
- 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 - 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.
- 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
- The History of SimpleSchema
- Installation
- Lingo
- Quick Start
- Validate an Object and Throw an Error
- Validate an Array of Objects and Throw an Error
- Validate a Meteor Method Argument and Satisfy
audit-argument-checks
- Validate an Object and Get the Errors
- Validate a MongoDB Modifier
- Enable Meteor Tracker Reactivity
- Automatically Clean the Object Before Validating It
- Set Default Options for One Schema
- Set Default Options for All Schemas
- Explicitly Clean an Object
- 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
- Contributors
- 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, new versions were released as an NPM package, which can be used in Meteor, NodeJS, or static browser apps. Afterwards it has been archived in favour of the NPM version.
In 2022/2023 the NPM package has dropped all Meteor compatibility and this package got released again, starting with the latest commit that included full Meteor support.
Installation
meteor add aldeed:simple-schema
Make sure, you installed version 2.0.0 or grater!
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
1import SimpleSchema from "meteor/aldeed:simple-schema"; 2 3new SimpleSchema({ 4 name: String, 5}).validate({ 6 name: 2, 7});
Validate an Array of Objects and Throw an Error
An error is thrown for the first invalid object found.
1import SimpleSchema from "meteor/aldeed:simple-schema"; 2 3new SimpleSchema({ 4 name: String, 5}).validate([{ name: "Bill" }, { name: 2 }]);
Validate a Meteor Method Argument and Satisfy audit-argument-checks
To avoid errors about not checking all arguments when you are using SimpleSchema to validate Meteor method arguments, you must pass check
as an option when creating your SimpleSchema instance.
1import SimpleSchema from "meteor/aldeed:simple-schema"; 2import { check } from "meteor/check"; 3import { Meteor } from "meteor/meteor"; 4 5SimpleSchema.defineValidationErrorTransform((error) => { 6 const ddpError = new Meteor.Error(error.message); 7 ddpError.error = "validation-error"; 8 ddpError.details = error.details; 9 return ddpError; 10}); 11 12const myMethodObjArgSchema = new SimpleSchema({ name: String }, { check }); 13 14Meteor.methods({ 15 myMethod(obj) { 16 myMethodObjArgSchema.validate(obj); 17 18 // Now do other method stuff knowing that obj satisfies the schema 19 }, 20});
Validate an Object and Get the Errors
1import SimpleSchema from "meteor/aldeed:simple-schema"; 2 3const validationContext = new SimpleSchema({ 4 name: String, 5}).newContext(); 6 7validationContext.validate({ 8 name: 2, 9}); 10 11console.log(validationContext.isValid()); 12console.log(validationContext.validationErrors());
Validate a MongoDB Modifier
1import SimpleSchema from "meteor/aldeed:simple-schema"; 2 3const validationContext = new SimpleSchema({ 4 name: String, 5}).newContext(); 6 7validationContext.validate( 8 { 9 $set: { 10 name: 2, 11 }, 12 }, 13 { modifier: true } 14); 15 16console.log(validationContext.isValid()); 17console.log(validationContext.validationErrors());
Enable Meteor Tracker Reactivity
1import SimpleSchema from "meteor/aldeed:simple-schema"; 2import { Tracker } from "meteor/tracker"; 3 4const validationContext = new SimpleSchema( 5 { 6 name: String, 7 }, 8 { tracker: Tracker } 9).newContext(); 10 11Tracker.autorun(function () { 12 console.log(validationContext.isValid()); 13 console.log(validationContext.validationErrors()); 14}); 15 16validationContext.validate({ 17 name: 2, 18}); 19 20validationContext.validate({ 21 name: "Joe", 22});
Passing in Tracker
causes the following functions to become reactive:
- ValidationContext#keyIsInvalid
- ValidationContext#keyErrorMessage
- ValidationContext#isValid
- ValidationContext#validationErrors
- SimpleSchema#label
Automatically Clean the Object Before Validating It
TO DO
Set Default Options for One Schema
1import SimpleSchema from "meteor/aldeed:simple-schema"; 2 3const mySchema = new SimpleSchema( 4 { 5 name: String, 6 }, 7 { 8 clean: { 9 autoConvert: true, 10 extendAutoValueContext: {}, 11 filter: false, 12 getAutoValues: true, 13 removeEmptyStrings: true, 14 removeNullsFromArrays: false, 15 trimStrings: true, 16 }, 17 humanizeAutoLabels: false, 18 requiredByDefault: true, 19 } 20);
These options will be used every time you clean or validate with this particular SimpleSchema instance.
Set Default Options for All Schemas
1import SimpleSchema from "meteor/aldeed:simple-schema"; 2 3SimpleSchema.constructorOptionDefaults({ 4 clean: { 5 filter: false, 6 }, 7 humanizeAutoLabels: false, 8}); 9 10// If you don't pass in any options, it will return the current defaults. 11console.log(SimpleSchema.constructorOptionDefaults());
These options will be used every time you clean or validate with any SimpleSchema instance, but can be overridden by options passed in to the constructor for a single instance.
Important notes:
- You must call
SimpleSchema.constructorOptionDefaults
before any of your schemas are created, so put it in an entry-point file and/or at the top of your code file. - In a large, complex project where SimpleSchema instances might be created by various JavaScript packages, there may be multiple
SimpleSchema
objects. In other words, theimport SimpleSchema
line in one package might be pulling in theSimpleSchema
object from one package while that line in another package pulls in a completely differentSimpleSchema
object. It will be difficult to know that this is happening unless you notice that your defaults are not being used by some of your schemas. To solve this, you can callSimpleSchema.constructorOptionDefaults
multiple times or adjust your package dependencies to ensure that only one version ofsimpl-schema
is pulled into your project.
Explicitly Clean an Object
1import SimpleSchema from "meteor/aldeed:simple-schema"; 2 3const mySchema = new SimpleSchema({ name: String }); 4const doc = { name: 123 }; 5const cleanDoc = mySchema.clean(doc); 6// cleanDoc is now mutated to hopefully have a better chance of passing validation 7console.log(typeof cleanDoc.name); // string
Works for a MongoDB modifier, too:
1import SimpleSchema from "meteor/aldeed:simple-schema"; 2 3const mySchema = new SimpleSchema({ name: String }); 4const modifier = { $set: { name: 123 } }; 5const cleanModifier = mySchema.clean(modifier); 6// doc is now mutated to hopefully have a better chance of passing validation 7console.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
1import SimpleSchema from "meteor/aldeed:simple-schema"; 2 3const schema = new SimpleSchema({ 4 name: String, 5 age: SimpleSchema.Integer, 6 registered: Boolean, 7});
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.
1import SimpleSchema from "meteor/aldeed:simple-schema"; 2 3const schema = new SimpleSchema({ 4 name: { 5 type: String, 6 max: 40, 7 }, 8 age: { 9 type: SimpleSchema.Integer, 10 optional: true, 11 }, 12 registered: { 13 type: Boolean, 14 defaultValue: false, 15 }, 16});
Mixing Shorthand with Longhand
You can use any combination of shorthand and longhand:
1import SimpleSchema from "meteor/aldeed:simple-schema"; 2 3const schema = new SimpleSchema({ 4 name: String, 5 age: { 6 type: SimpleSchema.Integer, 7 optional: true, 8 }, 9 registered: Boolean, 10});
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:
1{ 2 exp: /foo/; 3}
is equivalent to:
1{ 2 exp: { type: String, regEx: /foo/ } 3}
You can also set the schema key to an array of some type:
1{ 2 friends: [String], 3}
is equivalent to:
1{ 2 friends: { type: Array }, 3 'friends.$': { type: String }, 4}
Note: This only applies to shorthand definitions, not to the longhand definition. This example will throw an error { friends: { type: [String] } }
even though it was valid in the meteor-version of this package.
Multiple Definitions For One Key
You can define two or more different ways in which a key will be considered valid:
1import SimpleSchema from "meteor/aldeed:simple-schema"; 2 3const schema = new SimpleSchema({ 4 id: SimpleSchema.oneOf(String, SimpleSchema.Integer), 5 name: String, 6});
And this can be done in any mixture of shorthand and longhand:
1import SimpleSchema from "meteor/aldeed:simple-schema"; 2 3const schema = new SimpleSchema({ 4 id: SimpleSchema.oneOf( 5 { 6 type: String, 7 min: 16, 8 max: 16, 9 }, 10 { 11 type: SimpleSchema.Integer, 12 min: 0, 13 } 14 ), 15 name: String, 16});
When one of the allowed types is an object, use a subschema. Don't mix the object property definitions in with the main schema.
Correct:
1import SimpleSchema from "meteor/aldeed:simple-schema"; 2 3const objSchema = new SimpleSchema({ 4 _id: String, 5}); 6 7const schema = new SimpleSchema({ 8 foo: SimpleSchema.oneOf(String, objSchema), 9});
Incorrect:
1import SimpleSchema from "meteor/aldeed:simple-schema"; 2 3const schema = new SimpleSchema({ 4 foo: SimpleSchema.oneOf(String, Object), 5 "foo._id": { 6 type: String, 7 optional: true, 8 }, 9});
NOTE: Multiple definitions is still an experimental feature and may not work as you expect in complex situations, such as where one of the valid definitions is an object or array. By reporting any weirdness you experience, you can help make it more robust.
Extending Schemas
If there are certain fields that are repeated in many of your schemas, it can be useful to define a SimpleSchema instance just for those fields and then merge them into other schemas:
1import SimpleSchema from "meteor/aldeed:simple-schema"; 2import { idSchema, addressSchema } from "./sharedSchemas"; 3 4const schema = new SimpleSchema({ 5 name: String, 6}); 7schema.extend(idSchema); 8schema.extend(addressSchema);
Overriding When Extending
If the key appears in both schemas, the definition will be extended such that the result is the combination of both definitions.
1import SimpleSchema from "meteor/aldeed:simple-schema"; 2import { idSchema, addressSchema } from "./sharedSchemas"; 3 4const schema = new SimpleSchema({ 5 name: { 6 type: String, 7 min: 5, 8 }, 9}); 10schema.extend({ 11 name: { 12 type: String, 13 max: 15, 14 }, 15});
The above will result in the definition of the name
field becoming:
1{ 2 name: { 3 type: String, 4 min: 5, 5 max: 15, 6 }, 7}
Note also that a plain object was passed to extend
. If you pass a plain object, it is converted to a SimpleSchema
instance for you.
Subschemas
Similar to extending, you can also reference other schemas as a way to define objects that occur within the main object:
1import SimpleSchema from "meteor/aldeed:simple-schema"; 2import { addressSchema } from "./sharedSchemas"; 3 4const schema = new SimpleSchema({ 5 name: String, 6 homeAddress: addressSchema, 7 billingAddress: { 8 type: addressSchema, 9 optional: true, 10 }, 11});
Extracting Schemas
Sometimes you have one large SimpleSchema object, and you need just a subset of it for some purpose.
To pull out certain schema keys into a new schema, you can use the pick
method:
1import SimpleSchema from "meteor/aldeed:simple-schema"; 2 3const schema = new SimpleSchema({ 4 firstName: String, 5 lastName: String, 6 username: String, 7}); 8 9const nameSchema = schema.pick("firstName", "lastName");
To keep all but certain keys in a new schema, you can use the omit
method:
1import SimpleSchema from "meteor/aldeed:simple-schema"; 2 3const schema = new SimpleSchema({ 4 firstName: String, 5 lastName: String, 6 username: String, 7}); 8 9const nameSchema = schema.omit("username");
To pull a subschema out of an Object
key in a larger schema, you can use getObjectSchema
:
1import SimpleSchema from "meteor/aldeed:simple-schema"; 2 3const schema = new SimpleSchema({ 4 firstName: String, 5 lastName: String, 6 address: Object, 7 "address.street1": String, 8 "address.street2": { type: String, optional: true }, 9 "address.city": String, 10 "address.state": String, 11 "address.postalCode": String, 12}); 13 14const addressSchema = schema.getObjectSchema("address"); 15 16// addressSchema is now the same as this: 17// new SimpleSchema({ 18// street1: String, 19// street2: { type: String, optional: true }, 20// city: String, 21// state: String, 22// postalCode: String, 23// });
Raw Definition
Sometimes if you want to get the rawDefinition
of some schema just pass in the options { keepRawDefinition: true}
(if not arg is passed the value will be null). Example:
1const userSchema = new SimpleSchema( 2 { 3 name: String, 4 number: "SimpleSchema.Integer", 5 email: String, 6 }, 7 { keepRawDefintion: true } 8); 9userSchema.rawDefinition; 10//{ 11// name: String, 12// number: 'SimpleSchema.Integer', 13// email: String 14//}
Schema Keys
A basic schema key is just the name of the key (property) to expect in the objects that will be validated.
Use string keys with MongoDB-style dot notation to validate nested arrays and objects. For example:
1import SimpleSchema from "meteor/aldeed:simple-schema"; 2 3const schema = new SimpleSchema({ 4 mailingAddress: Object, 5 "mailingAddress.street": String, 6 "mailingAddress.city": String, 7});
To indicate array items, use a $
:
1import SimpleSchema from "meteor/aldeed:simple-schema"; 2 3const schema = new SimpleSchema({ 4 addresses: { 5 type: Array, 6 minCount: 1, 7 maxCount: 4, 8 }, 9 "addresses.$": Object, 10 "addresses.$.street": String, 11 "addresses.$.city": String, 12});
Schema Rules
Here are some specifics about the various rules you can define in your schema.
type
One of the following:
String
Number
SimpleSchema.Integer
(same asNumber
but with decimals/floats disallowed)Boolean
Object
Array
- Any custom or built-in class like
Date
- Another
SimpleSchema
instance, meaningObject
type with this schema SimpleSchema.oneOf(...)
, with multiple of the above types
label
Can also be a function that returns the label
A string that will be used to refer to this field in validation error messages. The default is an inflected (humanized) derivation of the key name itself. For example, the key "firstName" will have a default label of "First name" if you do not include the label
property in your definition.
You can use the labels
function to alter one or more labels on the fly:
1schema.labels({ 2 password: "Enter your password", 3});
If you have enabled Tracker reactivity, this method causes reactive labels to update.
To get the label for a field, use schema.label(fieldName)
, which returns a usable string. If you have enabled Tracker reactivity, this method is reactive.
optional
Can also be a function that returns true or false
By default, all keys are required. Set optional: true
to change that.
With complex keys, it might be difficult to understand what "required" means. Here's a brief explanation of how requiredness is interpreted:
- If
type
isArray
, then "required" means that key must have a value, but an empty array is fine. (If an empty array is not fine, add theminCount: 1
option.) - For array items (when the key name ends with ".$"), if
optional
is true, thennull
values are valid. If array items are required, then anynull
items will fail the type check. - If a key is required at a deeper level, the key must have a value only if the object it belongs to is present.
- When the object being validated is a Mongo modifier object, changes that would unset or
null
a required key result in validation errors.
That last point can be confusing, so let's look at a couple examples:
- Say you have a required key "friends.address.city" but "friends.address" is optional. If "friends.address" is set in the object you're validating, but "friends.address.city" is not, there is a validation error. However, if "friends.address" is not set, then there is no validation error for "friends.address.city" because the object it belongs to is not present.
- If you have a required key "friends.$.name", but the
friends
array has no objects in the object you are validating, there is no validation error for "friends.$.name". When thefriends
array does have objects, every present object is validated, and each object could potentially have a validation error if it is missing thename
property. For example, when there are two objects in the friends array and both are missing thename
property, there will be a validation error for both "friends.0.name" and "friends.1.name".
required
Can also be a function that returns true or false
If you would rather have all your schema keys be optional by default, pass the requiredByDefault: false
option and then use required: true
to make individual keys required.
1const schema = new SimpleSchema( 2 { 3 optionalProp: String, 4 requiredProp: { type: String, required: true }, 5 }, 6 { requiredByDefault: false } 7);
min/max
Can also be a function that returns the min/max value
- If
type
isNumber
orSimpleSchema.Integer
, these rules define the minimum or maximum numeric value. - If
type
isString
, these rules define the minimum or maximum string length. - If
type
isDate
, these rules define the minimum or maximum date, inclusive.
You can alternatively provide a function that takes no arguments and returns the appropriate minimum or maximum value. This is useful, for example, if the minimum Date for a field should be "today".
exclusiveMin/exclusiveMax
Can also be a function that returns true or false
Set to true
to indicate that the range of numeric values, as set by min/max, are to be treated as an exclusive range. Set to false
(default) to treat ranges as inclusive.
minCount/maxCount
Can also be a function that returns the minCount/maxCount value
Define the minimum or maximum array length. Used only when type is Array
.
allowedValues
Can also be a function that returns the array or the Set
of allowed values
An array or a Set
of values that are allowed. A key will be invalid if its value is not one of these.
You can use schema.getAllowedValuesForKey(key)
to get the allowed values array for a key.
Note: If you wish to restrict the items allowed in an Array
, the allowedValues
property must be on the array item definition.
1const schema = new SimpleSchema({ 2 myArray: { 3 type: Array, 4 }, 5 "myArray.$": { 6 type: String, 7 allowedValues: ["foo", "bar"], 8 }, 9});
regEx
Can also be a function that returns a regular expression or an array of them
Any regular expression that must be matched for the key to be valid, or an array of regular expressions that will be tested in order.
The SimpleSchema.RegEx
object defines standard regular expressions you can use as the value for the regEx
key.
SimpleSchema.RegEx.Email
for emails (uses a permissive regEx recommended by W3C, which most browsers use. Does not require a TLD)SimpleSchema.RegEx.EmailWithTLD
for emails that must have the TLD portion (.com, etc.). Emails likeme@localhost
andme@192.168.1.1
won't pass this one.SimpleSchema.RegEx.Domain
for external domains and the domain only (requires a tld like.com
)SimpleSchema.RegEx.WeakDomain
for less strict domains and IPv4 and IPv6SimpleSchema.RegEx.IP
for IPv4 or IPv6SimpleSchema.RegEx.IPv4
for just IPv4SimpleSchema.RegEx.IPv6
for just IPv6SimpleSchema.RegEx.Url
for http, https and ftp urlsSimpleSchema.RegEx.Id
for IDs generated byRandom.id()
of the random package, also usable to validate a relation id.SimpleSchema.RegEx.idOfLength(min, max)
for IDs generated byRandom.id(length)
where min/max define lower and upper bounds. Call without params for allowing an arbitrary length. Call withmin
only for fixed length. Call withmax = null
for fixed lower and arbitrary upper bounds.SimpleSchema.RegEx.ZipCode
for 5- and 9-digit ZIP codesSimpleSchema.RegEx.Phone
for phone numbers (taken from Google's libphonenumber library)
skipRegExCheckForEmptyStrings
Can also be a function that returns true or false
Set to true
when regEx
is set if you want an empty string to always pass validation, even though the regular expression may disallow it.
blackbox
If you have a key with type Object
, the properties of the object will be validated as well, so you must define all allowed properties in the schema. If this is not possible or you don't care to validate the object's properties, use the blackbox: true
option to skip validation for everything within the object.
Prior to SimpleSchema 2.0, objects that are instances of a custom class were considered to be blackbox by default. This is no longer true, so if you do not want your class instance validated, be sure to add blackbox: true
in your schema.
trim
Used by the cleaning process but not by validation
When you call simpleSchemaInstance.clean()
with trimStrings
set to true
, all string values are trimmed of leading and trailing whitespace. If you set trim
to false
for certain keys in their schema definition, those keys will be skipped.
custom
Refer to the Custom Validation section.
defaultValue
Used by the cleaning process but not by validation
Set this to any value that you want to be used as the default when an object does not include this field or has this field set to undefined
. This value will be injected into the object by a call to mySimpleSchema.clean()
with getAutovalues: true
.
Note the following points of confusion:
- A default value itself is not cleaned. So, for example, if your default value is "", it will not be removed by the
removeEmptyStrings
operation in the cleaning. - A default value is added only if there isn't a value set AND the parent object exists. Usually this is what you want, but if you need to ensure that it will always be added, you can add
defaultValue: {}
to all ancestor objects.
If you need more control, use the autoValue
option instead.
To get the defaultValue for a field, use schema.defaultValue(fieldName)
. It is a shorthand for schema.get(fieldName, 'defaultValue')
.
autoValue
Used by the cleaning process but not by validation
The autoValue
option allows you to specify a function that is called by simpleSchemaInstance.clean()
to potentially change the value of a property in the object being cleaned. This is a powerful feature that allows you to set up either forced values or default values, potentially based on the values of other fields in the object.
An autoValue
function this
context provides a variety of properties and methods to help you determine what you should return:
this.closestSubschemaFieldName
: If your schema is used as a subschema in another schema, this will be set to the name of the key that references the schema. Otherwise it will benull
.this.field()
: Use this method to get information about other fields. Pass a field name (schema key) as the only argument. The return object will haveisSet
,value
, andoperator
properties for that field.this.genericKey
: The generic schema key for which the autoValue is running ($
in place of actual array index).this.isInArrayItemObject
: True if we're traversing an object that's in an array.this.isInSubObject
: True if we're traversing an object that's somewhere within another object.this.isModifier
: True if this is running on a MongoDB modifier object.this.isSet
: True if the field is already set in the document or modifierthis.key
: The schema key for which the autoValue is running. This is usually known, but if your autoValue function is shared among various keys or if your schema is used as a subschema in another schema, this can be useful.this.obj
: The full object.this.operator
: If isSet = true and isUpdate = true, this contains the name of the update operator in the modifier in which this field is being changed. For example, if the modifier were{$set: {name: "Alice"}}
, in the autoValue function for thename
field,this.isSet
would be true,this.value
would be "Alice", andthis.operator
would be "$set".this.parentField()
: Use this method to get information about the parent object. Works the same way asfield()
.this.siblingField()
: Use this method to get information about other fields that have the same parent object. Works the same way asfield()
. This is helpful when you use sub-schemas or when you're dealing with arrays of objects.this.unset()
: Call this method to prevent the original value from being used when you return undefined.this.value
: If isSet = true, this contains the field's current (requested) value in the document or modifier.
If an autoValue
function does not return anything (i.e., returns undefined
), the field's value will be whatever the document or modifier says it should be. If that field is already in the document or modifier, it stays in the document or modifier with the same value. If it's not in the document or modifier, it's still not there. If you don't want it to be in the doc or modifier, you must call this.unset()
.
Any other return value will be used as the field's value. You may also return special pseudo-modifier objects for update operations. Examples are {$inc: 1}
and {$push: new Date}
.
autoValue gotchas
- If your autoValue for one field relies on the autoValue or defaultValue of another field, make sure that the other field is listed before the field that relies on it in the schema. autoValues are run in order from least nested, to most nested, so you can assume that parent values will be set, but for fields at the same level, schema order matters. Refer to issue #204.
- An
autoValue
function will always run during cleaning even if that field is not in the object being cleaned. This allows you to provide complex default values. If your function applies only when there is a value, you should addif (!this.isSet) return;
at the top.
Function Properties
You may have noticed that many of the rule properties can be set to functions that return the value. If you do this, the this
context within those functions will have the following properties:
this.field()
: Use this method to get information about other fields. Pass a field name (schema key) as the only argument. The return object will haveisSet
,value
, andoperator
properties for that field.this.genericKey
: The generic schema key for which the autoValue is running ($
in place of actual array index).this.isInArrayItemObject
: True if we're traversing an object that's in an array.this.isInSubObject
: True if we're traversing an object that's somewhere within another object.this.isModifier
: True if this is running on a MongoDB modifier object.this.isSet
: True if the field is already set in the document or modifierthis.key
: The schema key for which the autoValue is running. This is usually known, but if your autoValue function is shared among various keys or if your schema is used as a subschema in another schema, this can be useful.this.obj
: The full object.this.operator
: If isSet = true and isUpdate = true, this contains the name of the update operator in the modifier in which this field is being changed. For example, if the modifier were{$set: {name: "Alice"}}
, in the autoValue function for thename
field,this.isSet
would be true,this.value
would be "Alice", andthis.operator
would be "$set".this.parentField()
: Use this method to get information about the parent object. Works the same way asfield()
.this.siblingField()
: Use this method to get information about other fields that have the same parent object. Works the same way asfield()
. This is helpful when you use sub-schemas or when you're dealing with arrays of objects.this.validationContext
: The current validation contextthis.value
: If isSet = true, this contains the field's current (requested) value in the document or modifier.
Getting field properties
To obtain field's property value, just call the get
method.
1const schema = new SimpleSchema({ 2 friends: { 3 type: Array, 4 minCount: 0, 5 maxCount: 3, 6 }, 7}); 8 9schema.get("friends", "maxCount"); // 3
Validating Data
The Object to Validate
The object you pass in when validating can be a normal object, or it can be
a Mongo modifier object (with $set
, etc. keys). In other words, you can pass
in the exact object that you are going to pass to Collection.insert()
or
Collection.update()
. This is what the collection2 package does for you.
Ways to Perform Validation
There are three ways to validate an object against your schema:
- With a throwaway context, throwing an Error for the first validation error found (schema.validate())
- With a unique unnamed validation context, not throwing any Errors (schema.newContext().validate())
- With a unique named validation context, not throwing any Errors (schema.namedContext('someUniqueString').validate())
- With the default validation context, not throwing any Errors. (schema.namedContext().validate())
A validation context provides reactive methods for validating and checking the validation status of a particular object.
Named Validation Contexts
It's usually best to use a named validation context. That way, the context is automatically persisted by name, allowing you to easily rely on its reactive methods.
Here is an example of obtaining a named validation context:
1import SimpleSchema from "meteor/aldeed:simple-schema"; 2 3const schema = new SimpleSchema({ 4 name: String, 5}); 6 7const userFormValidationContext = schema.namedContext("userForm");
The first time you request a context with a certain name, it is created. Calling namedContext()
passing no arguments is equivalent to calling namedContext('default')
.
Unnamed Validation Contexts
To obtain an unnamed validation context, call newContext()
:
1import SimpleSchema from "meteor/aldeed:simple-schema"; 2 3const schema = new SimpleSchema({ 4 name: String, 5}); 6 7const myValidationContext = schema.newContext();
An unnamed validation context is not persisted anywhere. It can be useful when you need to see if a document is valid but you don't need any of the reactive methods for that context, or if you are going to keep the context reference in memory yourself.
Validating an Object
To validate an object against the schema in a validation context, call validationContextInstance.validate(obj, options)
. This method returns true
if the object is valid according to the schema or false
if it is not. It also stores a list of invalid fields and corresponding error messages in the context object and causes the reactive methods to react if you injected Tracker reactivity.
You can call myContext.isValid()
to see if the object last passed into validate()
was found to be valid. This is a reactive method that returns true
or false
.
For a list of options, see the Validation Options section.
Validating Only Some Keys in an Object
You may have the need to (re)validate certain keys while leaving any errors for other keys unchanged. For example, if you have several errors on a form and you want to revalidate only the invalid field the user is currently typing in. For this situation, call myContext.validate
with the keys
option set to an array of keys that should be validated. This may cause all of the reactive methods to react.
This method returns true
only if all the specified schema keys and their descendent keys are valid according to the schema. Otherwise it returns false
.
Validation Options
validate()
accepts the following options:
modifier
: Are you validating a Mongo modifier object? False by default.upsert
: Are you validating a Mongo modifier object potentially containing upsert operators? False by default.extendedCustomContext
: This object will be added to thethis
context in any custom validation functions that are run during validation. See the Custom Validation section.ignore
: An array of validation error types (in SimpleSchema.ErrorTypes enum) to ignore.keys
: An array of keys to validate. If not provided, revalidates the entire object.
Validating and Throwing ValidationErrors
- Call
mySimpleSchema.validate(obj, options)
to validateobj
against the schema and throw aValidationError
if invalid. - Call
SimpleSchema.validate(obj, schema, options)
static function as a shortcut formySimpleSchema.validate
if you don't want to createmySimpleSchema
first. Theschema
argument can be just the schema object, in which case it will be passed to theSimpleSchema
constructor for you. This is likecheck(obj, schema)
but without thecheck
dependency and with the ability to pass full schema error details back to a callback on the client. - Call
mySimpleSchema.validator()
to get a function that callsmySimpleSchema.validate
for whatever object is passed to it. This means you can dovalidate: mySimpleSchema.validator()
in the mdg:validated-method package. - Call
mySimpleSchema.getFormValidator()
to get a function that validates whatever object is passed to it and returns a Promise that resolves with errors. The returned function is compatible with the Composable Form Specification.
Customize the Error That is Thrown
You can defineValidationErrorTransform
one time somewhere in your code to customize the error or change it to a more specific type.
1import SimpleSchema from "meteor/aldeed:simple-schema"; 2 3SimpleSchema.defineValidationErrorTransform((error) => { 4 const customError = new MyCustomErrorType(error.message); 5 customError.errorList = error.details; 6 return customError; 7});
For example, in a Meteor app, in order to ensure that the error details are sent back to the client when throwing an error in a server method, you can convert it to a Meteor.Error
:
1import SimpleSchema from "meteor/aldeed:simple-schema"; 2 3SimpleSchema.defineValidationErrorTransform((error) => { 4 const ddpError = new Meteor.Error(error.message); 5 ddpError.error = "validation-error"; 6 ddpError.details = error.details; 7 return ddpError; 8});
Custom Field Validation
There are three ways to attach custom validation methods.
To add a custom validation function that is called for ALL keys in ALL schemas (for example, to publish a package that adds global support for some additional rule):
1SimpleSchema.addValidator(myFunction);
To add a custom validation function that is called for ALL keys for ONE schema:
1import SimpleSchema from "meteor/aldeed:simple-schema"; 2 3const schema = new SimpleSchema({ ... }); 4schema.addValidator(myFunction);
To add a custom validation function that is called for ONE key in ONE schema:
1import SimpleSchema from "meteor/aldeed:simple-schema"; 2 3const schema = new SimpleSchema({ 4 someKey: { 5 type: String, 6 custom: myFunction, 7 }, 8});
All custom validation functions work the same way. First, do the necessary custom validation, use this
to get whatever information you need. Then, if valid, return undefined
. If invalid, return an error type string. The error type string can be one of the built-in strings or any string you want.
- If you return a built-in string, it's best to use the
SimpleSchema.ErrorTypes
constants. - If you return a custom string, you'll usually want to define a message for it.
Within your custom validation function, this
provides the following properties:
key
: The name of the schema key (e.g., "addresses.0.street")genericKey
: The generic name of the schema key (e.g., "addresses.$.street")definition
: The schema definition object.isSet
: Does the object being validated have this key set?value
: The value to validate.operator
: The Mongo operator for which we're doing validation. Might benull
.validationContext
: The currentValidationContext
instancefield()
: Use this method to get information about other fields. Pass a field name (non-generic schema key) as the only argument. The return object will haveisSet
,value
, andoperator
properties for that field.siblingField()
: Use this method to get information about other fields that have the same parent object. Works the same way asfield()
. This is helpful when you use sub-schemas or when you're dealing with arrays of objects.addValidationErrors(errors)
: Call this to add validation errors for any key. In general, you should use this to add errors for other keys. To add an error for the current key, return the error type string. If you do use this to add an error for the current key, returnfalse
from your custom validation function.
NOTE: If you need to do some custom validation on the server and then display errors back on the client, refer to the Asynchronous Custom Validation on the Client section.
Custom Whole-Document Validators
Add a validator for all schemas:
1import SimpleSchema from "meteor/aldeed:simple-schema"; 2 3SimpleSchema.addDocValidator((obj) => { 4 // Must return an array, potentially empty, of objects with `name` and `type` string properties and optional `value` property. 5 return [{ name: "firstName", type: "TOO_SILLY", value: "Reepicheep" }]; 6});
Add a validator for one schema:
1import SimpleSchema from "meteor/aldeed:simple-schema"; 2 3const schema = new SimpleSchema({ ... }); 4schema.addDocValidator(obj => { 5 // Must return an array, potentially empty, of objects with `name` and `type` string properties and optional `value` property. 6 return [ 7 { name: 'firstName', type: 'TOO_SILLY', value: 'Reepicheep' } 8 ]; 9});
Whole-document validators have the following available on this
context:
this.ignoreTypes
: The value of theignore
option that was passed tovalidate
.this.isModifier
: True if this is running on a MongoDB modifier object.this.isUpsert
: True if this is running on a MongoDB modifier object that is for an upsert.this.keysToValidate
: The value of thekeys
option that was passed tovalidate
.this.mongoObject
: TheMongoObject
instance.this.obj
: The full object.this.schema
: The schema instance.this.validationContext
: TheValidationContext
instance.
Manually Adding a Validation Error
If you want to reactively display an arbitrary validation error and it is not possible to use a custom validation function (perhaps you have to call a function onSubmit
or wait for asynchronous results), you can add one or more errors to a validation context at any time by calling myContext.addValidationErrors(errors)
, where errors
is an array of error objects with the following format:
1{name: key, type: errorType, value: anyValue}
name
: The schema key as specified in the schema.type
: The type of error. Any string you want, or one of the strings in theSimpleSchema.ErrorTypes
list.value
: Optional. The value that was not valid. Will be used to replace the[value]
placeholder in error messages.
If you use a custom string for type
, be sure to define a message for it. (See Customizing Validation Messages).
Example:
1SimpleSchema.setDefaultMessages({ 2 messages: { 3 en: { 4 wrongPassword: "Wrong password", 5 }, 6 }, 7}); 8 9myValidationContext.addValidationErrors([ 10 { name: "password", type: "wrongPassword" }, 11]);
Asynchronous Custom Validation on the Client
NOTE: To use the unique
option in this example, you need to be in a Meteor app with the aldeed:schema-index
package added.
Validation runs synchronously for many reasons, and likely always will. This makes it difficult to wait for asynchronous results as part of custom validation. Here's one example of how you might validate that a username is unique on the client, without publishing all usernames to every client:
1username: { 2 type: String, 3 regEx: /^[a-z0-9A-Z_]{3,15}$/, 4 unique: true, 5 custom() { 6 if (Meteor.isClient && this.isSet) { 7 Meteor.call("accountsIsUsernameAvailable", this.value, (error, result) => { 8 if (!result) { 9 this.validationContext.addValidationErrors([{ 10 name: "username", 11 type: "notUnique" 12 }]); 13 } 14 }); 15 } 16 } 17}
Note that we're calling our "accountsIsUsernameAvailable" server method and waiting for an asynchronous result, which is a boolean that indicates whether that username is available. If it's taken, we manually invalidate the username
key with a "notUnique" error.
This doesn't change the fact that validation is synchronous. If you use this with an autoform and there are no validation errors, the form would still be submitted. However, the user creation would fail and a second or two later, the form would display the "notUnique" error, so the end result is very similar to actual asynchronous validation.
You can use a technique similar to this to work around asynchronicity issues in both client and server code.
Getting a List of Invalid Keys and Validation Error Messages
This is a reactive method if you have enabled Tracker reactivity.
Call myValidationContext.validationErrors()
to get the full array of validation errors. Each object in the array has at least two keys:
name
: The schema key as specified in the schema.type
: The type of error. SeeSimpleSchema.ErrorTypes
.
There may also be a value
property, which is the value that was invalid.
There may be a message
property, but usually the error message is constructed from message templates. You should call ctxt.keyErrorMessage(key)
to get a reactive message string rather than using error.message
directly.
Customizing Validation Messages
Error messages are managed by the message-box package.
In most cases you probably want to set default messages to be used by all SimpleSchema
instances. Example:
1SimpleSchema.setDefaultMessages({ 2 messages: { 3 en: { 4 too_long: "Too long!", 5 }, 6 }, 7});
The object syntax is the same as shown here for MessageBox.defaults
. When you call setDefaultMessages
, it simply extends the default defaults. Be sure to call it before you create any of your SimpleSchema instances
The MessageBox
instance for a specific schema instance is simpleSchemaInstance.messageBox
. You can call messages
function on this to update the messages for that schema only. Example:
1simpleSchemaInstance.messageBox.messages({ 2 en: { 3 too_long: "Too long!", 4 }, 5});
Other Validation Context Methods
myContext.keyIsInvalid(key)
returns true if the specified key is currently
invalid, or false if it is valid. This is a reactive method.
myContext.keyErrorMessage(key)
returns the error message for the specified
key if it is invalid. If it is valid, this method returns an empty string. This
is a reactive method.
Call myContext.reset()
if you need to reset the validation context, clearing out any invalid field messages and making it valid.
myContext.name
is set to the context name, if it is a named context. Create named contexts by calling schema.namedContext(name)
or new ValidationContext(schema, name)
.
Other SimpleSchema Methods
Call MySchema.schema([key])
to get the schema definition object. If you specify a key, then only the schema definition for that key is returned.
Note that this may not match exactly what you passed into the SimpleSchema constructor. The schema definition object is normalized internally, and this method returns the normalized copy.
Cleaning Objects
You can call simpleSchemaInstance.clean()
or simpleSchemaValidationContextInstance.clean()
to clean the object you're validating. Do this prior to validating it to avoid any avoidable validation errors.
The clean
function takes the object to be cleaned as its first argument and the following optional options as its second argument:
mutate
: The object is copied before being cleaned. If you don't mind mutating the object you are cleaning, you can passmutate: true
to get better performance.isModifier
: Is the first argument a modifier object? False by default.filter
:true
by default. Iftrue
, removes any keys not explicitly or implicitly allowed by the schema, which prevents errors being thrown for those keys during validation.autoConvert
:true
by default. Iftrue
, helps eliminate unnecessary validation messages by automatically converting values where possible.- Non-string values are converted to a String if the schema expects a String
- Strings that are numbers are converted to Numbers if the schema expects a Number
- Strings that are "true" or "false" are converted to Boolean if the schema expects a Boolean
- Numbers are converted to Boolean if the schema expects a Boolean, with 0 being
false
and all other numbers beingtrue
- Non-array values are converted to a one-item array if the schema expects an Array
removeEmptyStrings
: Remove keys in normal object or $set where the value is an empty string? True by default.trimStrings
: Remove all leading and trailing spaces from string values? True by default.getAutoValues
: RunautoValue
functions and inject automatic anddefaultValue
values? True by default.extendAutoValueContext
: This object will be added to thethis
context of autoValue functions.extendAutoValueContext
can be used to give yourautoValue
functions additional valuable information, such asuserId
. (Note that operations done using the Collection2 package automatically adduserId
to theautoValue
context already.)
You can also set defaults for any of these options in your SimpleSchema constructor options:
1const schema = new SimpleSchema( 2 { 3 name: String, 4 }, 5 { 6 clean: { 7 trimStrings: false, 8 }, 9 } 10);
NOTE: The Collection2 package always calls clean
before every insert, update, or upsert.
Dates
For consistency, if you care only about the date (year, month, date) portion and not the time, then use a Date
object set to the desired date at midnight UTC (note, the clean function won't strip out time). This goes for min
and max
dates, too. If you care only about the date
portion and you want to specify a minimum date, min
should be set to midnight UTC on the minimum date (inclusive).
Following these rules ensures maximum interoperability with HTML5 date inputs and usually just makes sense.
Best Practice Code Examples
Make a field conditionally required
If you have a field that should be required only in certain circumstances, first make the field optional, and then use a custom function similar to this:
1{ 2 field: { 3 type: String, 4 optional: true, 5 custom: function () { 6 let shouldBeRequired = this.field('saleType').value === 1; 7 8 if (shouldBeRequired) { 9 // inserts 10 if (!this.operator) { 11 if (!this.isSet || this.value === null || this.value === "") return SimpleSchema.ErrorTypes.REQUIRED; 12 } 13 14 // updates 15 else if (this.isSet) { 16 if (this.operator === "$set" && this.value === null || this.value === "") return SimpleSchema.ErrorTypes.REQUIRED; 17 if (this.operator === "$unset") return SimpleSchema.ErrorTypes.REQUIRED; 18 if (this.operator === "$rename") return SimpleSchema.ErrorTypes.REQUIRED; 19 } 20 } 21 } 22 } 23}
Where customCondition
is whatever should trigger it being required.
Validate one key against another
Here's an example of declaring one value valid or invalid based on another value using a custom validation function.
1SimpleSchema.messageBox.messages({ 2 en: { 3 passwordMismatch: "Passwords do not match", 4 }, 5}); 6 7MySchema = new SimpleSchema({ 8 password: { 9 type: String, 10 label: "Enter a password", 11 min: 8, 12 }, 13 confirmPassword: { 14 type: String, 15 label: "Enter the password again", 16 min: 8, 17 custom() { 18 if (this.value !== this.field("password").value) { 19 return "passwordMismatch"; 20 } 21 }, 22 }, 23});
Translation of Regular Expression Messages
The built-in English messages for regular expressions use a function, so to provide similar messages in another language, you can also use a function with a switch statement:
1messages: { 2 fr: { 3 regEx({ label, regExp }) { 4 switch (regExp) { 5 case (SimpleSchema.RegEx.Email.toString()): 6 case (SimpleSchema.RegEx.EmailWithTLD.toString()): 7 return "Cette adresse e-mail est incorrecte"; 8 case (SimpleSchema.RegEx.Domain.toString()): 9 case (SimpleSchema.RegEx.WeakDomain.toString()): 10 return "Ce champ doit être un domaine valide"; 11 case (SimpleSchema.RegEx.IP.toString()): 12 return "Cette adresse IP est invalide"; 13 case (SimpleSchema.RegEx.IPv4.toString()): 14 return "Cette adresse IPv4 est invalide"; 15 case (SimpleSchema.RegEx.IPv6.toString()): 16 return "Cette adresse IPv6 est invalide"; 17 case (SimpleSchema.RegEx.Url.toString()): 18 return "Cette URL est invalide"; 19 case (SimpleSchema.RegEx.Id.toString()): 20 return "Cet identifiant alphanumérique est invalide"; 21 case (SimpleSchema.RegEx.ZipCode.toString()): 22 return "Ce code postal est invalide"; 23 case (SimpleSchema.RegEx.Phone.toString()): 24 return "Ce numéro de téléphone est invalide"; 25 default: 26 return "Ce champ n'a pas passé la validation Regex"; 27 } 28 }, 29 } 30 } 31}
Debug Mode
Set SimpleSchema.debug = true
in your app before creating any named
validation contexts to cause all named validation contexts to automatically
log all invalid key errors to the browser console. This can be helpful while
developing an app to figure out why certain actions are failing validation.
Extending the Schema Options
You may find at some point that there is something extra you would really like to define within a schema for your package or app. However, if you add unrecognized options to your schema definition, you will get an error. To inform SimpleSchema about your custom option and avoid the error, you need to call SimpleSchema.extendOptions
. By way of example, here is how the Collection2 package adds the additional schema options it provides:
1SimpleSchema.extendOptions(["index", "unique", "denyInsert", "denyUpdate"]);
Obviously you need to ensure that extendOptions
is called before any SimpleSchema instances are created with those options.
Add On Packages
mxab:simple-schema-jsdoc Generate jsdoc from your schemas.
(Submit a PR to list your package here)
Contributors
This project exists thanks to all the people who contribute.
License
MIT
Contributing
Anyone is welcome to contribute. Before submitting a pull request, make sure that you've read our contribution guide.
Thanks
(Add your name if it's missing.)
- @mquandalle
- @Nemo64
- @DavidSichau