A schema validation package that supports direct validation of MongoDB update modifier objects.
npx @tessl/cli install tessl/npm-simpl-schema@3.4.00
# SimpleSchema
1
2
SimpleSchema 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.
3
4
## Package Information
5
6
- **Package Name**: simpl-schema
7
- **Package Type**: npm
8
- **Language**: TypeScript
9
- **Installation**: `npm install simpl-schema`
10
11
## Core Imports
12
13
```typescript
14
import SimpleSchema, { ValidationContext, toJsonSchema } from "simpl-schema";
15
```
16
17
For CommonJS:
18
19
```javascript
20
const SimpleSchema = require("simpl-schema").default;
21
const { ValidationContext, toJsonSchema } = require("simpl-schema");
22
```
23
24
## Basic Usage
25
26
```typescript
27
import SimpleSchema from "simpl-schema";
28
29
// Define a schema
30
const userSchema = new SimpleSchema({
31
name: {
32
type: String,
33
min: 1,
34
max: 200,
35
label: "Full Name"
36
},
37
email: {
38
type: String,
39
regEx: /^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$/,
40
label: "Email Address"
41
},
42
age: {
43
type: SimpleSchema.Integer,
44
min: 0,
45
max: 200,
46
optional: true
47
}
48
});
49
50
// Validate an object
51
const user = { name: "John Doe", email: "john@example.com", age: 30 };
52
userSchema.validate(user); // Throws error if invalid
53
54
// Or use validation context for error collection
55
const context = userSchema.newContext();
56
const isValid = context.validate(user);
57
if (!isValid) {
58
console.log(context.validationErrors());
59
}
60
61
// Clean and validate
62
const cleanedUser = userSchema.clean(user);
63
userSchema.validate(cleanedUser);
64
```
65
66
## Architecture
67
68
SimpleSchema is built around several key components:
69
70
- **SimpleSchema Class**: Main schema definition and validation engine with extensive configuration options
71
- **ValidationContext**: Manages validation state and error collection for detailed error reporting
72
- **Type System**: Supports all JavaScript types plus special types like Integer and Any with full TypeScript integration
73
- **Cleaning System**: Automatic type conversion, trimming, filtering, and value assignment before validation
74
- **MongoDB Integration**: Native support for validating MongoDB update modifier documents
75
- **Extensibility**: Custom validators, error message systems, and schema extension capabilities
76
77
## Capabilities
78
79
### Schema Definition
80
81
Core schema creation and manipulation functionality including field definitions, type constraints, and schema composition.
82
83
```typescript { .api }
84
class SimpleSchema {
85
constructor(
86
definition: SchemaDefinitionWithShorthand,
87
options?: SimpleSchemaOptions
88
);
89
90
extend(schema: SimpleSchema | PartialSchemaDefinitionWithShorthand): SimpleSchema;
91
clone(): SimpleSchema;
92
pick(...fields: string[]): SimpleSchema;
93
omit(...fields: string[]): SimpleSchema;
94
}
95
96
interface SimpleSchemaOptions {
97
clean?: CleanOptions;
98
defaultLabel?: string;
99
getErrorMessage?: GetErrorMessageFn;
100
humanizeAutoLabels?: boolean;
101
keepRawDefinition?: boolean;
102
requiredByDefault?: boolean;
103
}
104
```
105
106
[Schema Definition](./schema-definition.md)
107
108
### Validation
109
110
Comprehensive validation system supporting object validation, MongoDB modifiers, custom validators, and detailed error reporting.
111
112
```typescript { .api }
113
// Instance validation methods
114
validate(obj: any, options?: ValidationOptions): void;
115
validator(options?: ValidationOptions & {clean?: boolean, returnErrorsPromise?: boolean}): Function;
116
newContext(): ValidationContext;
117
namedContext(name?: string): ValidationContext;
118
119
// Static validation method
120
static validate(obj: any, schema: SimpleSchema | SchemaDefinition, options?: ValidationOptions): void;
121
122
interface ValidationOptions {
123
extendedCustomContext?: Record<string | number | symbol, unknown>;
124
ignore?: string[];
125
keys?: string[];
126
modifier?: boolean;
127
mongoObject?: any;
128
upsert?: boolean;
129
}
130
```
131
132
[Validation](./validation.md)
133
134
### Data Cleaning
135
136
Automatic data cleaning and normalization including type conversion, trimming, filtering, and automatic value assignment.
137
138
```typescript { .api }
139
clean(doc: Record<string | number | symbol, unknown>, options?: CleanOptions): Record<string | number | symbol, unknown>;
140
141
interface CleanOptions {
142
autoConvert?: boolean;
143
extendAutoValueContext?: CustomAutoValueContext;
144
filter?: boolean;
145
getAutoValues?: boolean;
146
isModifier?: boolean;
147
isUpsert?: boolean;
148
mongoObject?: MongoObject;
149
mutate?: boolean;
150
removeEmptyStrings?: boolean;
151
removeNullsFromArrays?: boolean;
152
trimStrings?: boolean;
153
}
154
```
155
156
[Data Cleaning](./data-cleaning.md)
157
158
### Validation Context
159
160
Validation context management for collecting validation errors, checking validity, and providing detailed error information.
161
162
```typescript { .api }
163
class ValidationContext {
164
validate(obj: ObjectToValidate, options?: ValidationOptions): boolean;
165
isValid(): boolean;
166
validationErrors(): ValidationError[];
167
setValidationErrors(errors: ValidationError[]): void;
168
addValidationErrors(errors: ValidationError[]): void;
169
reset(): void;
170
getErrorForKey(key: string, genericKey?: string): ValidationError | undefined;
171
keyIsInvalid(key: string, genericKey?: string): boolean;
172
keyErrorMessage(key: string, genericKey?: string): string;
173
clean(doc: Record<string | number | symbol, unknown>, options?: CleanOptions): Record<string | number | symbol, unknown>;
174
}
175
```
176
177
[Validation Context](./validation-context.md)
178
179
### Schema Introspection
180
181
Methods for examining schema structure, accessing field definitions, and navigating schema hierarchies.
182
183
```typescript { .api }
184
schema(): ResolvedSchemaDefinition;
185
schema(key: string): StandardSchemaKeyDefinition | null;
186
getDefinition(key: string, propList?: string[], functionContext?: Record<string, unknown>): StandardSchemaKeyDefinitionWithSimpleTypes;
187
objectKeys(keyPrefix?: string): string[];
188
allowsKey(key: string): boolean;
189
getQuickTypeForKey(key: string): string;
190
getAllowedValuesForKey(key: string): any[] | null;
191
label(key: string): string | null;
192
defaultValue(key: string): unknown;
193
```
194
195
[Schema Introspection](./schema-introspection.md)
196
197
### Utility Functions
198
199
Utility functions for schema conversion, type checking, and advanced schema operations.
200
201
```typescript { .api }
202
// JSON Schema conversion
203
function toJsonSchema(simpleSchema: SimpleSchema, id?: string): JSONSchema7;
204
205
// Type checking and schema groups
206
static isSimpleSchema(obj: unknown): boolean;
207
static oneOf(...definitions): SimpleSchemaGroup;
208
209
class SimpleSchemaGroup {
210
definitions: SchemaKeyDefinitionWithOneType[];
211
singleType: SupportedTypes;
212
clone(): SimpleSchemaGroup;
213
extend(otherGroup: SimpleSchemaGroup): void;
214
}
215
```
216
217
[Utility Functions](./utility-functions.md)
218
219
## Types
220
221
```typescript { .api }
222
// Core validation types
223
interface ValidationError {
224
message?: string;
225
name: string;
226
type: string;
227
value: any;
228
[prop: string]: any;
229
}
230
231
// Schema definition types
232
type SchemaDefinitionWithShorthand = Record<string, SchemaKeyDefinitionWithShorthand>;
233
type SchemaKeyDefinitionWithShorthand = StandardSchemaKeyDefinition | SchemaKeyDefinitionWithOneType | SupportedTypes | RegExpConstructor | SimpleSchemaGroup | SupportedTypes[];
234
235
interface SchemaKeyDefinitionBase {
236
autoValue?: AutoValueFunction;
237
defaultValue?: any;
238
label?: string | ((this: FunctionOptionContext) => string);
239
optional?: boolean | (() => boolean);
240
required?: boolean | (() => boolean);
241
242
// Type validation properties
243
allowedValues?: AllowedValues | (() => AllowedValues);
244
blackbox?: boolean;
245
custom?: ValidatorFunction;
246
exclusiveMax?: boolean;
247
exclusiveMin?: boolean;
248
maxCount?: number;
249
max?: number | Date | (() => number | Date);
250
minCount?: number;
251
min?: number | Date | (() => number | Date);
252
regEx?: RegExp | RegExp[];
253
skipRegExCheckForEmptyStrings?: boolean;
254
trim?: boolean;
255
}
256
257
interface SchemaKeyDefinitionWithOneType extends SchemaKeyDefinitionBase {
258
type: SupportedTypes;
259
}
260
261
// Supported types
262
type SupportedTypes =
263
| ArrayConstructor
264
| BooleanConstructor
265
| DateConstructor
266
| NumberConstructor
267
| StringConstructor
268
| ObjectConstructor
269
| '___Any___'
270
| typeof SimpleSchema.Integer
271
| SimpleSchema
272
| AnyClass
273
| RegExp;
274
275
// Function types
276
type AutoValueFunction = (this: AutoValueContext, obj: any) => any;
277
type ValidatorFunction = (this: ValidatorContext) => void | undefined | boolean | string | ValidationErrorResult;
278
type DocValidatorFunction = (this: DocValidatorContext, obj: Record<string, unknown>) => ValidationError[];
279
280
// Context types for validation functions
281
interface AutoValueContext {
282
key: string;
283
siblingKey: string;
284
parentKey: string;
285
isSet: boolean;
286
value: any;
287
operator: string;
288
field: (key: string) => { isSet: boolean; value: any; operator: string | null };
289
siblingField: (key: string) => { isSet: boolean; value: any; operator: string | null };
290
[prop: string]: any;
291
}
292
293
interface ValidatorContext {
294
key: string;
295
keyToValidate: string;
296
genericKey: string;
297
definition: StandardSchemaKeyDefinition;
298
isSet: boolean;
299
value: any;
300
operator: string;
301
validationContext: ValidationContext;
302
field: (key: string) => { isSet: boolean; value: any; operator: string | null };
303
siblingField: (key: string) => { isSet: boolean; value: any; operator: string | null };
304
[prop: string]: any;
305
}
306
307
interface DocValidatorContext {
308
isModifier: boolean;
309
isUpsert: boolean;
310
userId: string | null;
311
[prop: string]: any;
312
}
313
314
interface ValidationErrorResult {
315
type: string;
316
message?: string;
317
[prop: string]: any;
318
}
319
320
// Additional utility types
321
type AllowedValues = any[] | Set<any>;
322
type AnyClass = new (...args: any[]) => any;
323
324
interface FunctionOptionContext {
325
key?: string | null;
326
[prop: string]: unknown;
327
}
328
329
interface ClientError<T> {
330
error: {
331
type: string;
332
name: string;
333
[prop: string]: any;
334
};
335
details?: T;
336
[prop: string]: any;
337
}
338
```