A schema validation package that supports direct validation of MongoDB update modifier objects.
npx @tessl/cli install tessl/npm-simpl-schema@3.4.0SimpleSchema is a mature JavaScript/TypeScript schema validation library that provides comprehensive object validation with support for MongoDB update documents. It offers isomorphic functionality working in both NodeJS and modern browsers, with features including automatic type conversion, customizable error messages with localization support, object cleaning to fix potential validation errors automatically, and powerful autoValue/defaultValue systems.
npm install simpl-schemaimport SimpleSchema, { ValidationContext, toJsonSchema } from "simpl-schema";For CommonJS:
const SimpleSchema = require("simpl-schema").default;
const { ValidationContext, toJsonSchema } = require("simpl-schema");import SimpleSchema from "simpl-schema";
// Define a schema
const userSchema = new SimpleSchema({
name: {
type: String,
min: 1,
max: 200,
label: "Full Name"
},
email: {
type: String,
regEx: /^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$/,
label: "Email Address"
},
age: {
type: SimpleSchema.Integer,
min: 0,
max: 200,
optional: true
}
});
// Validate an object
const user = { name: "John Doe", email: "john@example.com", age: 30 };
userSchema.validate(user); // Throws error if invalid
// Or use validation context for error collection
const context = userSchema.newContext();
const isValid = context.validate(user);
if (!isValid) {
console.log(context.validationErrors());
}
// Clean and validate
const cleanedUser = userSchema.clean(user);
userSchema.validate(cleanedUser);SimpleSchema is built around several key components:
Core schema creation and manipulation functionality including field definitions, type constraints, and schema composition.
class SimpleSchema {
constructor(
definition: SchemaDefinitionWithShorthand,
options?: SimpleSchemaOptions
);
extend(schema: SimpleSchema | PartialSchemaDefinitionWithShorthand): SimpleSchema;
clone(): SimpleSchema;
pick(...fields: string[]): SimpleSchema;
omit(...fields: string[]): SimpleSchema;
}
interface SimpleSchemaOptions {
clean?: CleanOptions;
defaultLabel?: string;
getErrorMessage?: GetErrorMessageFn;
humanizeAutoLabels?: boolean;
keepRawDefinition?: boolean;
requiredByDefault?: boolean;
}Comprehensive validation system supporting object validation, MongoDB modifiers, custom validators, and detailed error reporting.
// Instance validation methods
validate(obj: any, options?: ValidationOptions): void;
validator(options?: ValidationOptions & {clean?: boolean, returnErrorsPromise?: boolean}): Function;
newContext(): ValidationContext;
namedContext(name?: string): ValidationContext;
// Static validation method
static validate(obj: any, schema: SimpleSchema | SchemaDefinition, options?: ValidationOptions): void;
interface ValidationOptions {
extendedCustomContext?: Record<string | number | symbol, unknown>;
ignore?: string[];
keys?: string[];
modifier?: boolean;
mongoObject?: any;
upsert?: boolean;
}Automatic data cleaning and normalization including type conversion, trimming, filtering, and automatic value assignment.
clean(doc: Record<string | number | symbol, unknown>, options?: CleanOptions): Record<string | number | symbol, unknown>;
interface CleanOptions {
autoConvert?: boolean;
extendAutoValueContext?: CustomAutoValueContext;
filter?: boolean;
getAutoValues?: boolean;
isModifier?: boolean;
isUpsert?: boolean;
mongoObject?: MongoObject;
mutate?: boolean;
removeEmptyStrings?: boolean;
removeNullsFromArrays?: boolean;
trimStrings?: boolean;
}Validation context management for collecting validation errors, checking validity, and providing detailed error information.
class ValidationContext {
validate(obj: ObjectToValidate, options?: ValidationOptions): boolean;
isValid(): boolean;
validationErrors(): ValidationError[];
setValidationErrors(errors: ValidationError[]): void;
addValidationErrors(errors: ValidationError[]): void;
reset(): void;
getErrorForKey(key: string, genericKey?: string): ValidationError | undefined;
keyIsInvalid(key: string, genericKey?: string): boolean;
keyErrorMessage(key: string, genericKey?: string): string;
clean(doc: Record<string | number | symbol, unknown>, options?: CleanOptions): Record<string | number | symbol, unknown>;
}Methods for examining schema structure, accessing field definitions, and navigating schema hierarchies.
schema(): ResolvedSchemaDefinition;
schema(key: string): StandardSchemaKeyDefinition | null;
getDefinition(key: string, propList?: string[], functionContext?: Record<string, unknown>): StandardSchemaKeyDefinitionWithSimpleTypes;
objectKeys(keyPrefix?: string): string[];
allowsKey(key: string): boolean;
getQuickTypeForKey(key: string): string;
getAllowedValuesForKey(key: string): any[] | null;
label(key: string): string | null;
defaultValue(key: string): unknown;Utility functions for schema conversion, type checking, and advanced schema operations.
// JSON Schema conversion
function toJsonSchema(simpleSchema: SimpleSchema, id?: string): JSONSchema7;
// Type checking and schema groups
static isSimpleSchema(obj: unknown): boolean;
static oneOf(...definitions): SimpleSchemaGroup;
class SimpleSchemaGroup {
definitions: SchemaKeyDefinitionWithOneType[];
singleType: SupportedTypes;
clone(): SimpleSchemaGroup;
extend(otherGroup: SimpleSchemaGroup): void;
}// Core validation types
interface ValidationError {
message?: string;
name: string;
type: string;
value: any;
[prop: string]: any;
}
// Schema definition types
type SchemaDefinitionWithShorthand = Record<string, SchemaKeyDefinitionWithShorthand>;
type SchemaKeyDefinitionWithShorthand = StandardSchemaKeyDefinition | SchemaKeyDefinitionWithOneType | SupportedTypes | RegExpConstructor | SimpleSchemaGroup | SupportedTypes[];
interface SchemaKeyDefinitionBase {
autoValue?: AutoValueFunction;
defaultValue?: any;
label?: string | ((this: FunctionOptionContext) => string);
optional?: boolean | (() => boolean);
required?: boolean | (() => boolean);
// Type validation properties
allowedValues?: AllowedValues | (() => AllowedValues);
blackbox?: boolean;
custom?: ValidatorFunction;
exclusiveMax?: boolean;
exclusiveMin?: boolean;
maxCount?: number;
max?: number | Date | (() => number | Date);
minCount?: number;
min?: number | Date | (() => number | Date);
regEx?: RegExp | RegExp[];
skipRegExCheckForEmptyStrings?: boolean;
trim?: boolean;
}
interface SchemaKeyDefinitionWithOneType extends SchemaKeyDefinitionBase {
type: SupportedTypes;
}
// Supported types
type SupportedTypes =
| ArrayConstructor
| BooleanConstructor
| DateConstructor
| NumberConstructor
| StringConstructor
| ObjectConstructor
| '___Any___'
| typeof SimpleSchema.Integer
| SimpleSchema
| AnyClass
| RegExp;
// Function types
type AutoValueFunction = (this: AutoValueContext, obj: any) => any;
type ValidatorFunction = (this: ValidatorContext) => void | undefined | boolean | string | ValidationErrorResult;
type DocValidatorFunction = (this: DocValidatorContext, obj: Record<string, unknown>) => ValidationError[];
// Context types for validation functions
interface AutoValueContext {
key: string;
siblingKey: string;
parentKey: string;
isSet: boolean;
value: any;
operator: string;
field: (key: string) => { isSet: boolean; value: any; operator: string | null };
siblingField: (key: string) => { isSet: boolean; value: any; operator: string | null };
[prop: string]: any;
}
interface ValidatorContext {
key: string;
keyToValidate: string;
genericKey: string;
definition: StandardSchemaKeyDefinition;
isSet: boolean;
value: any;
operator: string;
validationContext: ValidationContext;
field: (key: string) => { isSet: boolean; value: any; operator: string | null };
siblingField: (key: string) => { isSet: boolean; value: any; operator: string | null };
[prop: string]: any;
}
interface DocValidatorContext {
isModifier: boolean;
isUpsert: boolean;
userId: string | null;
[prop: string]: any;
}
interface ValidationErrorResult {
type: string;
message?: string;
[prop: string]: any;
}
// Additional utility types
type AllowedValues = any[] | Set<any>;
type AnyClass = new (...args: any[]) => any;
interface FunctionOptionContext {
key?: string | null;
[prop: string]: unknown;
}
interface ClientError<T> {
error: {
type: string;
name: string;
[prop: string]: any;
};
details?: T;
[prop: string]: any;
}