MCPcopy Index your code
hub / github.com/Meteor-Community-Packages/meteor-simple-schema

github.com/Meteor-Community-Packages/meteor-simple-schema @v3.0.0

Chat with this repo
repository ↗ · DeepWiki ↗ · release v3.0.0 ↗ · + Follow
166 symbols 464 edges 78 files 39 documented · 23%
What it actually does AI analysis from the code graph — generated when you open this
loading…
README

Meteor SimpleSchema

Meteor Community Package Test suite CodeQL Project Status: Active – The project has reached a stable, usable state and is being actively developed. GitHub License

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)! ☄️

Version 3.x.x

This is a breaking release. .clean(), .validate(), validation-context .validate(), validator functions, autoValue, custom validators, and whole-document validators may now use promises. Existing calls to isValid() and validationErrors() remain synchronous and report the last completed validation result. This is not compatible with collection2 4.x.x or autoform 8.x.x or lower.

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

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 greater!

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 "meteor/aldeed:simple-schema";

const schema = new SimpleSchema({
  name: String,
});

await schema.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 "meteor/aldeed:simple-schema";

const schema = new SimpleSchema({
  name: String,
});

await schema.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.

import SimpleSchema from "meteor/aldeed:simple-schema";
import { check } from "meteor/check";
import { Meteor } from "meteor/meteor";

SimpleSchema.defineValidationErrorTransform((error) => {
  const ddpError = new Meteor.Error(error.message);
  ddpError.error = "validation-error";
  ddpError.details = error.details;
  return ddpError;
});

const myMethodObjArgSchema = new SimpleSchema({ name: String }, { check });

Meteor.methods({
  async myMethod(obj) {
    await myMethodObjArgSchema.validate(obj);

    // Now do other method stuff knowing that obj satisfies the schema
  },
});

Validate an Object and Get the Errors

import SimpleSchema from "meteor/aldeed:simple-schema";

const validationContext = new SimpleSchema({
  name: String,
}).newContext();

await validationContext.validate({
  name: 2,
});

console.log(validationContext.isValid());
console.log(validationContext.validationErrors());

Validate a MongoDB Modifier

import SimpleSchema from "meteor/aldeed:simple-schema";

const validationContext = new SimpleSchema({
  name: String,
}).newContext();

await validationContext.validate(
  {
    $set: {
      name: 2,
    },
  },
  { modifier: true }
);

console.log(validationContext.isValid());
console.log(validationContext.validationErrors());

Enable Meteor Tracker Reactivity

import SimpleSchema from "meteor/aldeed: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());
});

await validationContext.validate({
  name: 2,
});

await validationContext.validate({
  name: "Joe",
});

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

import SimpleSchema from "meteor/aldeed:simple-schema";

const mySchema = new SimpleSchema(
  {
    name: String,
  },
  {
    clean: {
      autoConvert: true,
      extendAutoValueContext: {},
      filter: false,
      getAutoValues: true,
      removeEmptyStrings: true,
      removeNullsFromArrays: false,
      trimStrings: true,
    },
    humanizeAutoLabels: false,
    requiredByDefault: true,
  }
);

These options will be used every time you clean or validate with this particular SimpleSchema instance.

Set Default Options for All Schemas

import SimpleSchema from "meteor/aldeed:simple-schema";

SimpleSchema.constructorOptionDefaults({
  clean: {
    filter: false,
  },
  humanizeAutoLabels: false,
});

// If you don't pass in any options, it will return the current defaults.
console.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, the import SimpleSchema line in one package might be pulling in the SimpleSchema object from one package while that line in another package pulls in a completely different SimpleSchema 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 call SimpleSchema.constructorOptionDefaults multiple times or adjust your package dependencies to ensure that only one version of simpl-schema is pulled into your project.

Explicitly Clean an Object

import SimpleSchema from "meteor/aldeed:simple-schema";

const mySchema = new SimpleSchema({ name: String });
const doc = { name: 123 };
const cleanDoc = await 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:

```js import SimpleSchema from "meteor/aldeed:simple-schema";

const mySchema = new SimpleSchema({ name: String }); const modifier = { $set: { name: 123 } }; const cleanModifier = await mySchema.clean(mo

Core symbols most depended-on inside this repo

expectErrorOfTypeLength
called by 289
lib/testHelpers/expectErrorOfTypeLength.js
expectErrorLength
called by 159
lib/testHelpers/expectErrorLength.js
validate
called by 102
lib/SimpleSchema.js
clean
called by 87
lib/SimpleSchema.js
getTest
called by 59
lib/clean.tests.js
expectRequiredErrorLength
called by 49
lib/testHelpers/expectRequiredErrorLength.js
newContext
called by 41
lib/SimpleSchema.js
isFalse
called by 41
lib/SimpleSchema_regEx.tests.js

Shape

Function 81
Method 73
Class 12

Languages

TypeScript100%

Modules by API surface

lib/SimpleSchema.js48 symbols
lib/ValidationContext.js17 symbols
lib/doValidation.js11 symbols
lib/clean/AutoValueRunner.js9 symbols
lib/testHelpers/Address.js8 symbols
lib/SimpleSchema.tests.js8 symbols
lib/SimpleSchema_regEx.tests.js6 symbols
lib/SimpleSchemaGroup.js6 symbols
lib/humanize.js4 symbols
lib/clean.tests.js4 symbols
lib/testHelpers/testSchema.js3 symbols
lib/utility/getKeysWithValueInObj.js2 symbols

For agents

$ claude mcp add meteor-simple-schema \
  -- python -m otcore.mcp_server <graph>

⬇ download graph artifact

Ask about this repo answers extend the page