### Install SimpleSchema Source: https://github.com/longshotlabs/simpl-schema/blob/main/README.md Install the SimpleSchema package using npm or yarn. ```bash npm install simpl-schema # or yarn add simpl-schema ``` -------------------------------- ### Install SimpleSchema Source: https://github.com/longshotlabs/simpl-schema/blob/main/README.md Install the simpl-schema package using npm. Ensure you install the correct package, as there are similarly named packages available. ```bash npm install simpl-schema ``` -------------------------------- ### Validate One Key Against Another Source: https://github.com/longshotlabs/simpl-schema/blob/main/README.md Use a custom validation function to ensure that two fields have matching values. This example checks if 'confirmPassword' matches the 'password' field. ```javascript MySchema = new SimpleSchema({ password: { type: String, label: "Enter a password", min: 8, }, confirmPassword: { type: String, label: "Enter the password again", min: 8, custom() { if (this.value !== this.field("password").value) { return "passwordMismatch"; } }, }, }); ``` -------------------------------- ### Get Schema Property Value Source: https://github.com/longshotlabs/simpl-schema/blob/main/README.md Use the `get` method to retrieve the value of a specific schema property for a given field. This is useful for inspecting schema configurations. ```javascript const schema = new SimpleSchema({ friends: { type: Array, minCount: 0, maxCount: 3, }, }); schema.get("friends", "maxCount"); // 3 ``` -------------------------------- ### Getting Field Properties Source: https://github.com/longshotlabs/simpl-schema/blob/main/README.md Retrieve the schema definition for a specific field using the `schema()` method and accessing the field name. ```javascript import SimpleSchema from 'simpl-schema'; const schema = new SimpleSchema({ name: String, age: { type: Number, min: 0 } }); const ageSchemaDefinition = schema.schema().age; console.log(ageSchemaDefinition); // { type: Number, min: 0 } ``` -------------------------------- ### Validate Object and Get Errors Source: https://github.com/longshotlabs/simpl-schema/blob/main/README.md Validate an object against a schema and retrieve validation errors without throwing an exception. ```javascript import SimpleSchema from 'simpl-schema'; const schema = new SimpleSchema({ name: String, age: { type: Number, min: 0 } }); const errors = schema.newContext().validate({ name: 'John Doe', age: -5 }); if (errors) { console.log('Validation failed:', errors); } ``` -------------------------------- ### Get Raw Schema Definition Source: https://github.com/longshotlabs/simpl-schema/blob/main/README.md Retrieve the raw definition object of a schema by passing `{ keepRawDefinition: true }` during schema instantiation. The raw definition is stored in the `rawDefinition` property. ```javascript const userSchema = new SimpleSchema( { name: String, number: "SimpleSchema.Integer", email: String, }, { keepRawDefinition: true } ); userSchema.rawDefinition; //{ // name: String, // number: 'SimpleSchema.Integer', // email: String //} ``` -------------------------------- ### Get Normalized Schema Definition Source: https://github.com/longshotlabs/simpl-schema/blob/main/README.md Call `MySchema.schema([key])` to retrieve the normalized schema definition object. If a key is provided, only the definition for that key is returned. ```javascript MySchema.schema([key]) ``` -------------------------------- ### Define Allowed Values for Array Items Source: https://github.com/longshotlabs/simpl-schema/blob/main/README.md To restrict items within an array, define `allowedValues` on the array item's schema definition. This example restricts `myArray` items to 'foo' or 'bar'. ```javascript const schema = new SimpleSchema({ myArray: { type: Array, }, "myArray.$": { type: String, allowedValues: ["foo", "bar"], }, }); ``` -------------------------------- ### Conditionally Required Field Validation Source: https://github.com/longshotlabs/simpl-schema/blob/main/README.md Implement custom validation logic to make a field required only under specific conditions. This example checks if 'saleType' is 1 to determine if 'field' should be required. ```javascript { field: { type: String, optional: true, custom: function () { let shouldBeRequired = this.field('saleType').value === 1; if (shouldBeRequired) { // inserts if (!this.operator) { if (!this.isSet || this.value === null || this.value === "") return SimpleSchema.ErrorTypes.REQUIRED; } // updates else if (this.isSet) { if (this.operator === "$set" && this.value === null || this.value === "") return SimpleSchema.ErrorTypes.REQUIRED; if (this.operator === "$unset") return SimpleSchema.ErrorTypes.REQUIRED; if (this.operator === "$rename") return SimpleSchema.ErrorTypes.REQUIRED; } } } } } ``` -------------------------------- ### Validate Object and Get Errors Source: https://github.com/longshotlabs/simpl-schema/blob/main/README.md Validate an object and retrieve validation errors using a new context. This allows you to inspect errors without immediately throwing them. The 'name' field is expected to be a String. ```javascript import SimpleSchema from "simpl-schema"; const validationContext = new SimpleSchema({ name: String, }).newContext(); validationContext.validate({ name: 2, }); console.log(validationContext.isValid()); console.log(validationContext.validationErrors()); ``` -------------------------------- ### Get Error Message for a Specific Key Source: https://github.com/longshotlabs/simpl-schema/blob/main/README.md Call `keyErrorMessage(key)` on a validation context to retrieve the error message for a given key. Returns an empty string if the key is valid. ```javascript myContext.keyErrorMessage(key) ``` -------------------------------- ### Get All Validation Errors Source: https://github.com/longshotlabs/simpl-schema/blob/main/README.md Call `validationErrors()` on a validation context to retrieve an array of all validation errors. Each error object includes at least `name` and `type`, and may include `value` and `message`. ```javascript myValidationContext.validationErrors() ``` -------------------------------- ### autoValue Gotchas Source: https://github.com/longshotlabs/simpl-schema/blob/main/README.md Understand potential issues with 'autoValue', such as when it runs during updates or how to handle conditional auto-setting. ```javascript import SimpleSchema from 'simpl-schema'; const schema = new SimpleSchema({ updatedAt: { type: Date, autoValue: function () { // Only set on update, not on insert if (this.isUpdate) { return new Date(); } // If field is not present on insert, do nothing if (this.isInsert && !this.isSet) { return { $setOnInsert: new Date() // Set on insert only if not provided }; } } } }); ``` -------------------------------- ### Set Default Options for All Schemas Source: https://github.com/longshotlabs/simpl-schema/blob/main/README.md Set global default options for all SimpleSchema instances using `SimpleSchema.constructorOptionDefaults`. These defaults can be overridden by options provided to individual schema constructors. Call this early in your application's entry point. ```javascript import SimpleSchema from "simpl-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()); ``` -------------------------------- ### More Shorthand Schema Definitions Source: https://github.com/longshotlabs/simpl-schema/blob/main/README.md Illustrates additional shorthand options for defining schema properties, including type coercion and default values. ```javascript import SimpleSchema from 'simpl-schema'; const schema = new SimpleSchema({ // Shorthand for type: String, autoConvert: true name: String, // Shorthand for type: Number, min: 0, defaultValue: 18 age: [Number, { min: 0, defaultValue: 18 }], // Shorthand for type: Date, optional: true dob: Date }); ``` -------------------------------- ### Overriding When Extending Schemas Source: https://github.com/longshotlabs/simpl-schema/blob/main/README.md Demonstrates how to override properties from a base schema when extending it. This allows for specific adjustments in the extended schema. ```javascript import SimpleSchema from 'simpl-schema'; const baseSchema = new SimpleSchema({ name: { type: String, label: 'Name' } }); const extendedSchema = new SimpleSchema({ ...baseSchema.schema(), name: { type: String, label: 'Full Name', // Overridden label required: true // Added requirement } }); ``` -------------------------------- ### Define Schema with Shorthand Syntax Source: https://github.com/longshotlabs/simpl-schema/blob/main/README.md Use shorthand syntax for simple schema definitions by mapping property names directly to types. Simple Schema ensures properties are present and of the correct type. ```javascript import SimpleSchema from "simpl-schema"; const schema = new SimpleSchema({ name: String, age: SimpleSchema.Integer, registered: Boolean, }); ``` -------------------------------- ### Extract Schema Keys with pick Source: https://github.com/longshotlabs/simpl-schema/blob/main/README.md Create a new schema containing only specified keys from an existing schema. Useful for creating smaller schemas for specific purposes. ```javascript import SimpleSchema from "simpl-schema"; const schema = new SimpleSchema({ firstName: String, lastName: String, username: String, }); const nameSchema = schema.pick("firstName", "lastName"); ``` -------------------------------- ### Extend SimpleSchema Options Source: https://github.com/longshotlabs/simpl-schema/blob/main/README.md Use this to inform SimpleSchema about custom options you want to define in your schemas. Ensure this is called before creating any SimpleSchema instances that use these options. ```javascript SimpleSchema.extendOptions(["index", "unique", "denyInsert", "denyUpdate"]); ``` -------------------------------- ### Multiple Definitions for One Key Source: https://github.com/longshotlabs/simpl-schema/blob/main/README.md Define multiple possible types or configurations for a single schema key. This allows for more flexible data structures. ```javascript import SimpleSchema from 'simpl-schema'; const schema = new SimpleSchema({ value: [ String, // Allows string { type: Number, min: 0 } // Allows non-negative numbers ] }); ``` -------------------------------- ### Define Optional and Required Properties Source: https://github.com/longshotlabs/simpl-schema/blob/main/README.md Use `requiredByDefault: false` to make all properties optional by default, then explicitly set `required: true` for specific properties. ```javascript const schema = new SimpleSchema( { optionalProp: String, requiredProp: { type: String, required: true }, }, { requiredByDefault: false } ); ``` -------------------------------- ### Set Default Clean Options in SimpleSchema Constructor Source: https://github.com/longshotlabs/simpl-schema/blob/main/README.md Configure default cleaning options like trimming strings when initializing SimpleSchema. This affects all instances created with these options. ```javascript const schema = new SimpleSchema( { name: String, }, { clean: { trimStrings: false, }, } ); ``` -------------------------------- ### Mix Shorthand and Longhand Schema Definitions Source: https://github.com/longshotlabs/simpl-schema/blob/main/README.md Combine shorthand and longhand syntax within the same schema definition for flexibility. This allows for concise definitions of simple types and detailed definitions for others. ```javascript import SimpleSchema from "simpl-schema"; const schema = new SimpleSchema({ name: String, age: { type: SimpleSchema.Integer, optional: true, }, registered: Boolean, }); ``` -------------------------------- ### Define Schema with Shorthand Source: https://github.com/longshotlabs/simpl-schema/blob/main/README.md Define a SimpleSchema using shorthand notation for concise schema definitions. This is the most common way to define schemas. ```javascript import SimpleSchema from 'simpl-schema'; const schema = new SimpleSchema({ name: String, age: { type: Number, min: 0 }, email: { type: String, optional: true }, createdAt: Date }); ``` -------------------------------- ### Mixing Shorthand and Longhand Schema Definitions Source: https://github.com/longshotlabs/simpl-schema/blob/main/README.md Combine shorthand and longhand definitions within the same schema for flexibility. Use shorthand for common properties and longhand for specific configurations. ```javascript import SimpleSchema from 'simpl-schema'; const schema = new SimpleSchema({ name: String, // Shorthand age: { type: Number, min: 0 // Longhand }, email: { type: String, regEx: SimpleSchema.RegEx.Email // Longhand } }); ``` -------------------------------- ### Set Default Options for All Schemas Source: https://github.com/longshotlabs/simpl-schema/blob/main/README.md Set default validation options globally for all SimpleSchema instances. Use this to configure behavior across your application. ```javascript import SimpleSchema from 'simpl-schema'; SimpleSchema.setDefaultOptions({ autoConvert: true, clean: false }); // All new SimpleSchema instances will now use these defaults. ``` -------------------------------- ### Enable Debug Mode for Validation Logging Source: https://github.com/longshotlabs/simpl-schema/blob/main/README.md Activate debug mode by setting `SimpleSchema.debug = true`. This will log all invalid key errors to the browser console for named validation contexts, aiding development. ```javascript SimpleSchema.debug = true; ``` -------------------------------- ### Extending Schemas Source: https://github.com/longshotlabs/simpl-schema/blob/main/README.md Create a new schema that extends an existing one, inheriting its properties and allowing for additions or modifications. This promotes code reuse. ```javascript import SimpleSchema from 'simpl-schema'; const baseSchema = new SimpleSchema({ name: String }); const extendedSchema = new SimpleSchema({ ...baseSchema.schema(), // Spread existing schema properties age: { type: Number, min: 0 } }); ``` -------------------------------- ### Schema Rules: min/max Source: https://github.com/longshotlabs/simpl-schema/blob/main/README.md The 'min' and 'max' rules set the minimum and maximum allowed values for numeric or date types. They are inclusive. ```javascript import SimpleSchema from 'simpl-schema'; const schema = new SimpleSchema({ age: { type: Number, min: 0, max: 120 }, startDate: { type: Date, min: new Date(2020, 0, 1) // January 1, 2020 } }); ``` -------------------------------- ### Set Default Options for One Schema Source: https://github.com/longshotlabs/simpl-schema/blob/main/README.md Configure default options for a specific SimpleSchema instance. These options, such as 'clean', 'humanizeAutoLabels', and 'requiredByDefault', will be applied to all clean and validate operations for this schema. ```javascript import SimpleSchema from "simpl-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, } ); ``` -------------------------------- ### Define Schema with Multiple Allowed Types (oneOf) Source: https://github.com/longshotlabs/simpl-schema/blob/main/README.md Use `SimpleSchema.oneOf` to specify that a key can be one of several different types or definitions. This is useful for handling variations in data. ```javascript import SimpleSchema from "simpl-schema"; const schema = new SimpleSchema({ id: SimpleSchema.oneOf(String, SimpleSchema.Integer), name: String, }); ``` ```javascript import SimpleSchema from "simpl-schema"; const schema = new SimpleSchema({ id: SimpleSchema.oneOf( { type: String, min: 16, max: 16, }, { type: SimpleSchema.Integer, min: 0, } ), name: String, }); ``` ```javascript import SimpleSchema from "simpl-schema"; const objSchema = new SimpleSchema({ _id: String, }); const schema = new SimpleSchema({ foo: SimpleSchema.oneOf(String, objSchema), }); ``` -------------------------------- ### Add Global Whole-Document Validator Source: https://github.com/longshotlabs/simpl-schema/blob/main/README.md Implement a validator that checks the entire document for all schemas. It must return an array of error objects. ```javascript import SimpleSchema from "simpl-schema"; SimpleSchema.addDocValidator((obj) => { // Must return an array, potentially empty, of objects with `name` and `type` string properties and optional `value` property. return [{ name: "firstName", type: "TOO_SILLY", value: "Reepicheep" }]; }); ``` -------------------------------- ### Define Schema with Longhand Source: https://github.com/longshotlabs/simpl-schema/blob/main/README.md Define a SimpleSchema using longhand notation for more explicit control over schema properties. This is useful for complex configurations. ```javascript import SimpleSchema from 'simpl-schema'; const schema = new SimpleSchema({ name: { type: String, label: 'Full Name', required: true }, age: { type: Number, label: 'Age', min: 0, max: 120 }, email: { type: String, label: 'Email Address', regEx: SimpleSchema.RegEx.Email } }); ``` -------------------------------- ### Schema Rules: exclusiveMin/exclusiveMax Source: https://github.com/longshotlabs/simpl-schema/blob/main/README.md The 'exclusiveMin' and 'exclusiveMax' rules set the minimum and maximum allowed values, excluding the boundary values themselves. ```javascript import SimpleSchema from 'simpl-schema'; const schema = new SimpleSchema({ score: { type: Number, exclusiveMin: 0, exclusiveMax: 100 } }); ``` -------------------------------- ### Create Unnamed Validation Context Source: https://github.com/longshotlabs/simpl-schema/blob/main/README.md Create an unnamed validation context with `schema.newContext()`. This context is not persisted and is useful for one-off validation checks where the context reference is managed manually. ```javascript import SimpleSchema from "simpl-schema"; const schema = new SimpleSchema({ name: String, }); const myValidationContext = schema.newContext(); ``` -------------------------------- ### Define Schema with Longhand Syntax Source: https://github.com/longshotlabs/simpl-schema/blob/main/README.md Use longhand syntax to define additional rules beyond data types, such as `max`, `optional`, and `defaultValue`. This provides more control over schema validation. ```javascript import SimpleSchema from "simpl-schema"; const schema = new SimpleSchema({ name: { type: String, max: 40, }, age: { type: SimpleSchema.Integer, optional: true, }, registered: { type: Boolean, defaultValue: false, }, }); ``` -------------------------------- ### Schema Rules: label Source: https://github.com/longshotlabs/simpl-schema/blob/main/README.md The 'label' rule provides a human-readable name for a schema key, often used in UI elements or error messages. ```javascript import SimpleSchema from 'simpl-schema'; const schema = new SimpleSchema({ firstName: { type: String, label: 'First Name' }, lastName: { type: String, label: 'Last Name' } }); ``` -------------------------------- ### Set Default Options for One Schema Source: https://github.com/longshotlabs/simpl-schema/blob/main/README.md Set default validation options for a specific schema instance. These options will be used for all validations performed on this schema unless overridden. ```javascript import SimpleSchema from 'simpl-schema'; const schema = new SimpleSchema({ name: String }, { autoConvert: false, clean: true }); // Validation on this schema will now have autoConvert: false and clean: true by default. ``` -------------------------------- ### Configure Global Validation Message Customization Source: https://github.com/longshotlabs/simpl-schema/blob/main/README.md Set `globalThis.simpleSchemaGlobalConfig.getErrorMessage` to customize validation messages globally for all schemas. Schema-specific `getErrorMessage` functions take precedence. ```javascript globalThis.simpleSchemaGlobalConfig = { getErrorMessage(error, label) { if (error.type === 'too_long') return `${label} is too long!` // Returning undefined will fall back to using defaults } }; ``` -------------------------------- ### Add Schema-Specific Whole-Document Validator Source: https://github.com/longshotlabs/simpl-schema/blob/main/README.md Create a validator for a single schema instance that inspects the entire document. The validator should return an array of error objects. ```javascript import SimpleSchema from 'simpl-schema'; const schema = new SimpleSchema({ ... }); schema.addDocValidator(obj => { // Must return an array, potentially empty, of objects with `name` and `type` string properties and optional `value` property. return [ { name: 'firstName', type: 'TOO_SILLY', value: 'Reepicheep' } ]; }); ``` -------------------------------- ### Function Properties in SimpleSchema Source: https://github.com/longshotlabs/simpl-schema/blob/main/README.md Define schema keys whose values are functions. SimpleSchema handles these appropriately during validation and cleaning. ```javascript import SimpleSchema from 'simpl-schema'; const schema = new SimpleSchema({ callback: Function }); ``` -------------------------------- ### Extend Schema with Overriding Source: https://github.com/longshotlabs/simpl-schema/blob/main/README.md Extend an existing schema with new definitions. If a key exists in both schemas, the definitions are combined. Plain objects passed to extend are converted to SimpleSchema instances. ```javascript import SimpleSchema from "simpl-schema"; import { idSchema, addressSchema } from "./sharedSchemas"; const schema = new SimpleSchema({ name: { type: String, min: 5, }, }); schema.extend({ name: { type: String, max: 15, }, }); ``` -------------------------------- ### Convert SimpleSchema to JSONSchema Source: https://github.com/longshotlabs/simpl-schema/blob/main/README.md Converts a SimpleSchema instance to its JSONSchema representation. Requires importing the `toJsonSchema` function. ```typescript import { toJsonSchema } from 'simpl-schema' const schema = new SimpleSchema({ name: String }) const jsonSchema = toJsonSchema(schema) ``` -------------------------------- ### Define Schema with Regular Expression Type Source: https://github.com/longshotlabs/simpl-schema/blob/main/README.md When a schema key is set to a regular expression, the type defaults to `String`, and the string value must match the provided regular expression. ```javascript { exp: /foo/; } ``` -------------------------------- ### Schema Rules: minCount/maxCount Source: https://github.com/longshotlabs/simpl-schema/blob/main/README.md The 'minCount' and 'maxCount' rules specify the minimum and maximum number of items allowed in an array. ```javascript import SimpleSchema from 'simpl-schema'; const schema = new SimpleSchema({ tags: { type: Array, minCount: 1, maxCount: 5 }, 'tags.$': String }); ``` -------------------------------- ### Create Named Validation Context Source: https://github.com/longshotlabs/simpl-schema/blob/main/README.md Obtain a named validation context using `schema.namedContext()`. This context is persisted by name and can be reused. If no name is provided, it defaults to 'default'. ```javascript import SimpleSchema from "simpl-schema"; const schema = new SimpleSchema({ name: String, }); const userFormValidationContext = schema.namedContext("userForm"); ``` -------------------------------- ### Extend Schema with Shared Definitions Source: https://github.com/longshotlabs/simpl-schema/blob/main/README.md Merge existing SimpleSchema instances into a new schema to reuse common field definitions. This promotes consistency and reduces redundancy. ```javascript import SimpleSchema from "simpl-schema"; import { idSchema, addressSchema } from "./sharedSchemas"; const schema = new SimpleSchema({ name: String, }); schema.extend(idSchema); schema.extend(addressSchema); ``` -------------------------------- ### Extracting Schemas Source: https://github.com/longshotlabs/simpl-schema/blob/main/README.md Extract the schema definition object from a SimpleSchema instance. This is useful for extending schemas or programmatically manipulating them. ```javascript import SimpleSchema from 'simpl-schema'; const schema = new SimpleSchema({ name: String, age: Number }); const schemaObject = schema.schema(); console.log(schemaObject); // { name: { type: String }, age: { type: Number } } ``` -------------------------------- ### Schema Rules: type Source: https://github.com/longshotlabs/simpl-schema/blob/main/README.md The 'type' rule specifies the expected data type for a schema key. It can be a primitive type, a constructor, or an array of allowed types. ```javascript import SimpleSchema from 'simpl-schema'; const schema = new SimpleSchema({ name: String, // type: String age: Number, // type: Number isActive: Boolean, // type: Boolean tags: Array, // type: Array 'tags.$': String, // type for array elements config: Object, // type: Object 'config.timeout': Number, // type for nested object property mixedType: [String, Number] // Allows String or Number }); ``` -------------------------------- ### Extract Schema Keys with omit Source: https://github.com/longshotlabs/simpl-schema/blob/main/README.md Create a new schema excluding specified keys from an existing schema. Useful for creating schemas that omit certain sensitive or irrelevant fields. ```javascript import SimpleSchema from "simpl-schema"; const schema = new SimpleSchema({ firstName: String, lastName: String, username: String, }); const nameSchema = schema.omit("username"); ``` -------------------------------- ### Validate Object and Throw Error Source: https://github.com/longshotlabs/simpl-schema/blob/main/README.md Use this snippet to validate a single object against a schema and immediately throw an error if validation fails. Ensure the 'name' field is a String. ```javascript import SimpleSchema from "simpl-schema"; new SimpleSchema({ name: String, }).validate({ name: 2, }); ``` -------------------------------- ### Validate Object and Throw Error Source: https://github.com/longshotlabs/simpl-schema/blob/main/README.md Validate an object against a schema. Throws an error if validation fails. ```javascript import SimpleSchema from 'simpl-schema'; const schema = new SimpleSchema({ name: String, age: { type: Number, min: 0 } }); try { schema.validate({ name: 'John Doe', age: 30 }); console.log('Validation successful!'); } catch (error) { console.error(error.message); } ``` -------------------------------- ### Schema Rules: trim Source: https://github.com/longshotlabs/simpl-schema/blob/main/README.md The 'trim' rule automatically trims whitespace from the beginning and end of string values during cleaning. This helps standardize string inputs. ```javascript import SimpleSchema from 'simpl-schema'; const schema = new SimpleSchema({ name: { type: String, trim: true // Trim whitespace } }); ``` -------------------------------- ### Add Global Custom Validator Source: https://github.com/longshotlabs/simpl-schema/blob/main/README.md Use this to add a custom validation function that applies to all keys in all schemas. This is useful for creating reusable validation packages. ```javascript SimpleSchema.addValidator(myFunction); ``` -------------------------------- ### Clean an Object with Simple Schema Source: https://github.com/longshotlabs/simpl-schema/blob/main/README.md Use the `clean` method to mutate an object to have a better chance of passing validation. This works for both regular objects and MongoDB update documents. ```javascript import SimpleSchema from "simpl-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 ``` ```javascript import SimpleSchema from "simpl-schema"; const mySchema = new SimpleSchema({ name: String }); const updateDoc = { $set: { name: 123 } }; const cleanUpdateDoc = mySchema.clean(updateDoc); // doc is now mutated to hopefully have a better chance of passing validation console.log(typeof cleanUpdateDoc.$set.name); // string ``` -------------------------------- ### Schema Rules: custom validation Source: https://github.com/longshotlabs/simpl-schema/blob/main/README.md Define custom validation logic for a schema key using the 'custom' rule. This allows for complex validation scenarios beyond built-in rules. ```javascript import SimpleSchema from 'simpl-schema'; const schema = new SimpleSchema({ password: { type: String, custom: function () { if (this.value.length < 6) { return 'tooShort'; // Return an error reason string } } } }); ``` -------------------------------- ### Validate Array of Objects and Throw Error Source: https://github.com/longshotlabs/simpl-schema/blob/main/README.md Validate an array of objects against a schema. Throws an error if any object fails validation. ```javascript import SimpleSchema from 'simpl-schema'; const schema = new SimpleSchema({ name: String, age: { type: Number, min: 0 } }); try { schema.validate([{ name: 'John Doe', age: 30 }, { name: 'Jane Doe', age: 25 }]); console.log('Validation successful!'); } catch (error) { console.error(error.message); } ``` -------------------------------- ### Schema Rules: skipRegExCheckForEmptyStrings Source: https://github.com/longshotlabs/simpl-schema/blob/main/README.md The 'skipRegExCheckForEmptyStrings' rule allows empty strings to bypass regular expression validation. This is useful when a field is optional but should be validated if present. ```javascript import SimpleSchema from 'simpl-schema'; const schema = new SimpleSchema({ website: { type: String, regEx: SimpleSchema.RegEx.Url, skipRegExCheckForEmptyStrings: true } }); ``` -------------------------------- ### Schema Rules: regEx Source: https://github.com/longshotlabs/simpl-schema/blob/main/README.md The 'regEx' rule validates a string field against a regular expression. SimpleSchema provides common regex patterns. ```javascript import SimpleSchema from 'simpl-schema'; const schema = new SimpleSchema({ email: { type: String, regEx: SimpleSchema.RegEx.Email }, url: { type: String, regEx: SimpleSchema.RegEx.Url } }); ``` -------------------------------- ### Define Schema with Subschemas Source: https://github.com/longshotlabs/simpl-schema/blob/main/README.md Reference other schemas as a way to define objects that occur within the main object. This is useful for organizing complex schemas. ```javascript import SimpleSchema from "simpl-schema"; import { addressSchema } from "./sharedSchemas"; const schema = new SimpleSchema({ name: String, homeAddress: addressSchema, billingAddress: { type: addressSchema, optional: true, }, }); ``` -------------------------------- ### Raw Definition in SimpleSchema Source: https://github.com/longshotlabs/simpl-schema/blob/main/README.md Use the 'raw' definition type for schema keys when you need to store arbitrary data or metadata associated with a field, without it being treated as a validation rule. ```javascript import SimpleSchema from 'simpl-schema'; const schema = new SimpleSchema({ name: String, customData: { type: Object, blackbox: true, // Treat as raw data defaultValue: { info: 'some data' } } }); ``` -------------------------------- ### Update Schema Labels Source: https://github.com/longshotlabs/simpl-schema/blob/main/README.md Alter one or more labels on a schema instance using the `labels` function. This is useful for customizing error messages. ```javascript schema.labels({ password: "Enter your password", }); ``` -------------------------------- ### Check if a Key is Invalid Source: https://github.com/longshotlabs/simpl-schema/blob/main/README.md Use `keyIsInvalid(key)` on a validation context to check if a specific schema key currently has validation errors. ```javascript myContext.keyIsInvalid(key) ``` -------------------------------- ### Define Schema with Array Type Source: https://github.com/longshotlabs/simpl-schema/blob/main/README.md Define an array type by setting the schema key to an array of the element type. This shorthand automatically sets the main key to `type: Array` and defines the element type. ```javascript { friends: [String], } ``` -------------------------------- ### Validating an Object Source: https://github.com/longshotlabs/simpl-schema/blob/main/README.md Validate an entire object against the schema using a validation context. This method stores errors within the context and returns a boolean indicating validity. ```APIDOC ## validate(obj, options) ### Description Validates an object against the schema within a validation context. Stores invalid fields and error messages in the context. ### Method `validationContextInstance.validate(obj, options)` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **obj** (Object) - The object to validate. - **options** (Object) - Optional validation options. ### Request Example ```javascript const isValid = myContext.validate(myObject, { modifier: false, upsert: false, extendedCustomContext: {}, ignore: [], keys: [] }); ``` ### Response #### Success Response (true) Returns `true` if the object is valid. #### Error Response (false) Returns `false` if the object is invalid. Errors are stored in the validation context. ### Related Methods - `myContext.isValid()`: Returns `true` or `false` based on the last validation result. ``` -------------------------------- ### Validate Array of Objects and Throw Error Source: https://github.com/longshotlabs/simpl-schema/blob/main/README.md Validate an array of objects. An error is thrown for the first invalid object encountered in the array. The 'name' field must be a String. ```javascript import SimpleSchema from "simpl-schema"; new SimpleSchema({ name: String, }).validate([{ name: "Bill" }, { name: 2 }]); ``` -------------------------------- ### Validating and Throwing ValidationErrors Source: https://github.com/longshotlabs/simpl-schema/blob/main/README.md Validate an object and throw a `ValidationError` if it's invalid. This includes static methods and options for transforming errors. ```APIDOC ## Schema Validation with Error Throwing ### Description Provides methods to validate data and throw `ValidationError` upon failure. Includes static methods and error transformation capabilities. ### Methods 1. **`mySimpleSchema.validate(obj, options)`** Validates `obj` against `mySimpleSchema` and throws `ValidationError` if invalid. 2. **`SimpleSchema.validate(obj, schema, options)`** Static function to validate `obj` against `schema` without instantiating `SimpleSchema`. Throws `ValidationError` if invalid. 3. **`mySimpleSchema.validator()`** Returns a function that takes an object and calls `mySimpleSchema.validate` on it. 4. **`mySimpleSchema.getFormValidator()`** Returns a function that validates an object and returns a Promise resolving with errors. Compatible with Composable Form Specification. ### Parameters for `validate` methods - **obj** (Object) - The object to validate. - **schema** (Object) - The schema object to validate against (used with static `SimpleSchema.validate`). - **options** (Object) - Optional validation options (e.g., `modifier`, `upsert`, `extendedCustomContext`, `ignore`, `keys`). ### Error Handling - **`SimpleSchema.defineValidationErrorTransform(transformFunction)`** Defines a function to customize or transform the `ValidationError` before it is thrown. The `transformFunction` receives the original error object and should return the transformed error. ### Request Example (Transforming Errors) ```javascript import SimpleSchema from "simpl-schema"; SimpleSchema.defineValidationErrorTransform((error) => { // Example: Convert to a custom error type const customError = new MyCustomErrorType(error.message); customError.errorList = error.details; return customError; }); // Example: Convert to Meteor.Error on the server SimpleSchema.defineValidationErrorTransform((error) => { const ddpError = new Meteor.Error(error.message); ddpError.error = "validation-error"; ddpError.details = error.details; return ddpError; }); ``` ``` -------------------------------- ### Automatically Clean Object Before Validation Source: https://github.com/longshotlabs/simpl-schema/blob/main/README.md Clean an object to automatically convert types, remove unsupported properties, and add default values before validation. This helps ensure the object is valid. ```javascript import SimpleSchema from 'simpl-schema'; const schema = new SimpleSchema({ name: String, age: { type: Number, min: 0, defaultValue: 18 }, email: { type: String, optional: true } }); const doc = { name: 'John Doe', age: '30', extraField: 'should be removed' }; schema.clean(doc); console.log(doc); // { name: 'John Doe', age: 30 } ``` -------------------------------- ### Explicitly Clean an Object Source: https://github.com/longshotlabs/simpl-schema/blob/main/README.md Manually clean an object using a schema without performing validation. This is useful for preparing data before it's used or validated. ```javascript import SimpleSchema from 'simpl-schema'; const schema = new SimpleSchema({ name: String, age: { type: Number, defaultValue: 18 } }); const doc = { name: 'John Doe', extraField: 'should be removed' }; schema.clean(doc); console.log(doc); // { name: 'John Doe', age: 18 } ``` -------------------------------- ### Add Key-Specific Custom Validator Source: https://github.com/longshotlabs/simpl-schema/blob/main/README.md Define a custom validation function for a single key within a specific schema. The `custom` property in the key's definition is used for this. ```javascript import SimpleSchema from "simpl-schema"; const schema = new SimpleSchema({ someKey: { type: String, custom: myFunction, }, }); ``` -------------------------------- ### Customize Validation Messages for a Schema Source: https://github.com/longshotlabs/simpl-schema/blob/main/README.md Provide a `getErrorMessage` function in the schema options to customize validation messages. This function receives the error object and label, and should return a custom message string or `undefined` to fall back to defaults. ```javascript const schema = new SimpleSchema({ name: String }, { getErrorMessage(error, label) { if (error.type === 'too_long') return `${label} is too long!` // Returning undefined will fall back to using defaults } }) ``` -------------------------------- ### Reset Validation Context Source: https://github.com/longshotlabs/simpl-schema/blob/main/README.md Use `reset()` on a validation context to clear all invalid field messages and make the context valid. ```javascript myContext.reset() ``` -------------------------------- ### Schema Rules: required Source: https://github.com/longshotlabs/simpl-schema/blob/main/README.md The 'required' rule explicitly marks a schema key as mandatory. This is the default behavior for keys without 'optional: true'. ```javascript import SimpleSchema from 'simpl-schema'; const schema = new SimpleSchema({ name: { type: String, required: true // Explicitly required }, age: Number }); ``` -------------------------------- ### Add Schema-Specific Custom Validator Source: https://github.com/longshotlabs/simpl-schema/blob/main/README.md Attach a custom validation function to a specific schema instance. This function will be called for all keys within that schema. ```javascript import SimpleSchema from 'simpl-schema'; const schema = new SimpleSchema({ ... }); schema.addValidator(myFunction); ``` -------------------------------- ### Schema Rules: allowedValues Source: https://github.com/longshotlabs/simpl-schema/blob/main/README.md The 'allowedValues' rule restricts a field's value to a predefined set of options. ```javascript import SimpleSchema from 'simpl-schema'; const schema = new SimpleSchema({ status: { type: String, allowedValues: ['pending', 'processing', 'completed', 'failed'] } }); ``` -------------------------------- ### Subschemas in SimpleSchema Source: https://github.com/longshotlabs/simpl-schema/blob/main/README.md Define nested schemas (subschemas) to structure complex objects. This improves organization and reusability of schema definitions. ```javascript import SimpleSchema from 'simpl-schema'; const addressSchema = new SimpleSchema({ street: String, city: String }); const userSchema = new SimpleSchema({ name: String, address: { type: Object, schema: addressSchema // Nested schema } }); ``` -------------------------------- ### Define Nested Object Schema Source: https://github.com/longshotlabs/simpl-schema/blob/main/README.md Use MongoDB-style dot notation to define keys for nested objects within a schema. This allows for validation of complex, deeply nested data structures. ```javascript import SimpleSchema from "simpl-schema"; const schema = new SimpleSchema({ mailingAddress: Object, "mailingAddress.street": String, "mailingAddress.city": String, }); ``` -------------------------------- ### Schema Rules: optional Source: https://github.com/longshotlabs/simpl-schema/blob/main/README.md The 'optional' rule marks a schema key as not required. If a key is optional, it can be omitted from the validated object. ```javascript import SimpleSchema from 'simpl-schema'; const schema = new SimpleSchema({ name: String, email: { type: String, optional: true // This field can be omitted } }); ``` -------------------------------- ### Schema Rules: blackbox Source: https://github.com/longshotlabs/simpl-schema/blob/main/README.md The 'blackbox' rule treats an object or array field as opaque, meaning its contents will not be validated. This is useful for fields containing arbitrary data or complex structures not managed by SimpleSchema. ```javascript import SimpleSchema from 'simpl-schema'; const schema = new SimpleSchema({ metadata: { type: Object, blackbox: true // Do not validate contents of metadata } }); ``` -------------------------------- ### Validating Multiple Objects in an Array Source: https://github.com/longshotlabs/simpl-schema/blob/main/README.md Validate an array of objects. The validation stops at the first error encountered. ```APIDOC ## validate(arrayOfObjects) ### Description Validates all objects within an array against the schema. Validation stops and returns `false` upon encountering the first invalid object. ### Method `myContext.validate(arrayOfObjects)` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **arrayOfObjects** (Array) - An array of objects to validate. ### Request Example ```javascript const isValid = myContext.validate([object1, object2, object3]); ``` ### Response #### Success Response (true) Returns `true` if all objects in the array are valid. #### Error Response (false) Returns `false` if any object in the array is invalid. The first encountered error determines the result. ``` -------------------------------- ### Extract Object Subschema with getObjectSchema Source: https://github.com/longshotlabs/simpl-schema/blob/main/README.md Pull a subschema out of an Object key within a larger schema. This returns a new SimpleSchema instance representing the nested object's structure. ```javascript import SimpleSchema from "simpl-schema"; const schema = new SimpleSchema({ firstName: String, lastName: String, address: Object, "address.street1": String, "address.street2": { type: String, optional: true }, "address.city": String, "address.state": String, "address.postalCode": String, }); const addressSchema = schema.getObjectSchema("address"); // addressSchema is now the same as this: // new SimpleSchema({ // street1: String, // street2: { type: String, optional: true }, // city: String, // state: String, // postalCode: String, // }); ``` -------------------------------- ### Define Nested Array Schema Source: https://github.com/longshotlabs/simpl-schema/blob/main/README.md Use the `$` symbol with dot notation to define rules for array items within a schema. This allows for validation of objects or values within arrays. ```javascript import SimpleSchema from "simpl-schema"; const schema = new SimpleSchema({ addresses: { type: Array, minCount: 1, maxCount: 4, }, "addresses.$": Object, "addresses.$.street": String, "addresses.$.city": String, }); ``` -------------------------------- ### Schema Rules: autoValue Source: https://github.com/longshotlabs/simpl-schema/blob/main/README.md The 'autoValue' rule automatically sets a field's value based on a function. This is useful for dynamic values like timestamps or generated IDs. ```javascript import SimpleSchema from 'simpl-schema'; const schema = new SimpleSchema({ createdAt: { type: Date, autoValue: function () { if (this.isInsert) { return new Date(); } } } }); ``` -------------------------------- ### Add Custom Validation Errors to Context Source: https://github.com/longshotlabs/simpl-schema/blob/main/README.md Use `addValidationErrors` to manually add validation errors to a context. Errors should be objects with `name`, `type`, and optionally `value` properties. This is useful when errors cannot be caught by automatic validation. ```javascript myValidationContext.addValidationErrors([ { name: "password", type: "wrongPassword" }, ]); ``` -------------------------------- ### Schema Rules: defaultValue Source: https://github.com/longshotlabs/simpl-schema/blob/main/README.md The 'defaultValue' rule assigns a default value to a schema key if it is not provided in the validated object. This ensures the key always has a value. ```javascript import SimpleSchema from 'simpl-schema'; const schema = new SimpleSchema({ status: { type: String, allowedValues: ['active', 'inactive'], defaultValue: 'active' } }); ``` -------------------------------- ### Validating Only Some Keys in an Object Source: https://github.com/longshotlabs/simpl-schema/blob/main/README.md Revalidate specific keys within an object, leaving other errors unchanged. Useful for form validation where users edit one field at a time. ```APIDOC ## validate(obj, { keys: [...] }) ### Description Validates only the specified keys and their descendant keys within an object. Useful for revalidating individual fields in a form. ### Method `myContext.validate(obj, { keys: [...] })` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **obj** (Object) - The object containing the keys to validate. - **keys** (Array) - An array of strings representing the keys to validate. ### Request Example ```javascript const isValid = myContext.validate(myObject, { keys: ['fieldName1', 'nested.fieldName2'] }); ``` ### Response #### Success Response (true) Returns `true` if all specified keys and their descendants are valid. #### Error Response (false) Returns `false` if any of the specified keys or their descendants are invalid. ``` -------------------------------- ### Validate MongoDB Update Document Source: https://github.com/longshotlabs/simpl-schema/blob/main/README.md Validate a MongoDB update document to ensure it conforms to the schema. This is useful for server-side validation before applying updates. ```javascript import SimpleSchema from 'simpl-schema'; const schema = new SimpleSchema({ name: String, age: { type: Number, min: 0 } }); const updateDoc = { $set: { age: 30 }, $unset: { name: '' } }; try { schema.validate(updateDoc, { modifier: true }); console.log('Update document is valid.'); } catch (error) { console.error('Update document is invalid:', error.message); } ``` -------------------------------- ### Define Custom ValidationError Transform Source: https://github.com/longshotlabs/simpl-schema/blob/main/README.md Use `defineValidationErrorTransform` to customize the error thrown by SimpleSchema. This allows you to transform the default error into a more specific type, such as a `MyCustomErrorType` or a `Meteor.Error` for server-side validation in Meteor applications. ```javascript import SimpleSchema from "simpl-schema"; SimpleSchema.defineValidationErrorTransform((error) => { const customError = new MyCustomErrorType(error.message); customError.errorList = error.details; return customError; }); ``` ```javascript import SimpleSchema from "simpl-schema"; SimpleSchema.defineValidationErrorTransform((error) => { const ddpError = new Meteor.Error(error.message); ddpError.error = "validation-error"; ddpError.details = error.details; return ddpError; }); ``` -------------------------------- ### Validate MongoDB Update Document Source: https://github.com/longshotlabs/simpl-schema/blob/main/README.md Validate a MongoDB update document, typically used with the 'modifier: true' option. This checks if the update operation conforms to the schema. The 'name' field is expected to be a String. ```javascript import SimpleSchema from "simpl-schema"; const validationContext = new SimpleSchema({ name: String, }).newContext(); validationContext.validate( { $set: { name: 2, }, }, { modifier: true } ); console.log(validationContext.isValid()); console.log(validationContext.validationErrors()); ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.