or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

Files

docs

index.md
tile.json

index.mddocs/

0

# jsonschema

1

2

jsonschema is a comprehensive JSON Schema validator for JavaScript and Node.js that supports JSON Schema draft-07. It provides both simple validation functions for quick usage and a full Validator class with advanced features including custom formats, custom keywords, schema dereferencing, error localization, and pre-validation hooks.

3

4

## Package Information

5

6

- **Package Name**: jsonschema

7

- **Package Type**: npm

8

- **Language**: JavaScript (with TypeScript definitions)

9

- **Installation**: `npm install jsonschema`

10

11

## Core Imports

12

13

```javascript

14

const { validate, Validator } = require('jsonschema');

15

```

16

17

ES modules:

18

19

```javascript

20

import { validate, Validator } from 'jsonschema';

21

```

22

23

## Basic Usage

24

25

```javascript

26

const { validate, Validator } = require('jsonschema');

27

28

// Simple validation

29

const result = validate(4, {"type": "number"});

30

console.log(result.valid); // true

31

32

// Advanced validation with schema references

33

const v = new Validator();

34

35

// Add referenced schema

36

const addressSchema = {

37

"id": "/SimpleAddress",

38

"type": "object",

39

"properties": {

40

"lines": {"type": "array", "items": {"type": "string"}},

41

"zip": {"type": "string"},

42

"city": {"type": "string"},

43

"country": {"type": "string"}

44

},

45

"required": ["country"]

46

};

47

48

const personSchema = {

49

"id": "/SimplePerson",

50

"type": "object",

51

"properties": {

52

"name": {"type": "string"},

53

"address": {"$ref": "/SimpleAddress"},

54

"votes": {"type": "integer", "minimum": 1}

55

}

56

};

57

58

v.addSchema(addressSchema, '/SimpleAddress');

59

const result = v.validate(person, personSchema);

60

```

61

62

## Architecture

63

64

jsonschema is built around several key components:

65

66

- **Simple API**: Standalone `validate` function for basic validation needs

67

- **Validator Class**: Advanced validator with schema registry, custom formats, and custom keywords

68

- **Result System**: Comprehensive result objects with detailed error information and validation status

69

- **Schema Management**: Built-in schema scanning, reference resolution, and registry system

70

- **Extensibility**: Support for custom formats, custom validation keywords, and hooks

71

72

## Capabilities

73

74

### Simple Validation

75

76

Quick validation using the standalone validate function for basic use cases.

77

78

```javascript { .api }

79

/**

80

* Validates an instance against a JSON schema

81

* @param instance - The data to validate

82

* @param schema - The JSON schema to validate against

83

* @param options - Optional validation options

84

* @returns ValidatorResult with validation status and errors

85

*/

86

function validate(instance: any, schema: any, options?: Options): ValidatorResult;

87

```

88

89

### Advanced Validator Class

90

91

Full-featured validator class with schema registry, custom formats, and extensible validation.

92

93

```javascript { .api }

94

/**

95

* Advanced JSON Schema validator with schema registry and extensibility

96

*/

97

class Validator {

98

constructor();

99

100

/** Custom format validation functions */

101

customFormats: {[formatName: string]: CustomFormat};

102

103

/** Registry of loaded schemas */

104

schemas: {[id: string]: Schema};

105

106

/** Array of unresolved schema references */

107

unresolvedRefs: string[];

108

109

/** Custom validation attributes/keywords */

110

attributes: {[property: string]: CustomProperty};

111

112

/**

113

* Add a schema to the validator's registry

114

* @param schema - The schema to add

115

* @param uri - Optional URI for the schema

116

* @returns The added schema or void

117

*/

118

addSchema(schema?: Schema, uri?: string): Schema|void;

119

120

/**

121

* Validate an instance against a schema

122

* @param instance - The data to validate

123

* @param schema - The schema to validate against

124

* @param options - Validation options

125

* @param ctx - Schema context (internal use)

126

* @returns ValidatorResult with validation status and errors

127

*/

128

validate(instance: any, schema: Schema, options?: Options, ctx?: SchemaContext): ValidatorResult;

129

}

130

```

131

132

### Validation Results

133

134

Comprehensive result objects providing detailed validation status, errors, and metadata.

135

136

```javascript { .api }

137

/**

138

* Result of a validation operation

139

*/

140

class ValidatorResult {

141

constructor(instance: any, schema: Schema, options: Options, ctx: SchemaContext);

142

143

/** The validated instance */

144

instance: any;

145

146

/** The schema used for validation */

147

schema: Schema;

148

149

/** Property path to the validated data */

150

propertyPath: string;

151

152

/** Array of validation errors */

153

errors: ValidationError[];

154

155

/** Whether validation succeeded */

156

valid: boolean;

157

158

/**

159

* Add a validation error to the result

160

* @param detail - Error message string or ErrorDetail object

161

* @returns The created ValidationError

162

*/

163

addError(detail: string|ErrorDetail): ValidationError;

164

165

/**

166

* String representation of the validation result

167

* @returns String describing the result

168

*/

169

toString(): string;

170

}

171

172

/**

173

* Individual validation error

174

*/

175

class ValidationError {

176

constructor(message?: string, instance?: any, schema?: Schema, propertyPath?: any, name?: string, argument?: any);

177

178

/** Array path to the error location */

179

path: (string|number)[];

180

181

/** String property path (e.g., "instance.foo.bar") */

182

property: string;

183

184

/** Human-readable error message */

185

message: string;

186

187

/** Schema that failed validation */

188

schema: string|Schema;

189

190

/** Instance value that failed */

191

instance: any;

192

193

/** Name of the failed validation keyword */

194

name: string;

195

196

/** Additional argument for the failed keyword */

197

argument: any;

198

199

/**

200

* String representation of the error

201

* @returns Formatted error message

202

*/

203

toString(): string;

204

}

205

206

/**

207

* Error thrown when using throwError options

208

*/

209

class ValidatorResultError extends Error {

210

/** The validated instance */

211

instance: any;

212

213

/** The schema used for validation */

214

schema: Schema;

215

216

/** Validation options used */

217

options: Options;

218

219

/** Validation errors that occurred */

220

errors: ValidationError;

221

}

222

223

/**

224

* Error thrown for invalid schemas

225

*/

226

class SchemaError extends Error {

227

constructor(msg: string, schema: Schema);

228

229

/** The invalid schema */

230

schema: Schema;

231

232

/** Error description */

233

message: string;

234

}

235

```

236

237

### Schema Management

238

239

Schema scanning, reference resolution, and registry management for complex schema relationships.

240

241

```javascript { .api }

242

/**

243

* Scan a schema for references and sub-schemas

244

* @param base - Base URI for resolving references

245

* @param schema - Schema to scan

246

* @returns SchemaScanResult with found schemas and references

247

*/

248

function scan(base: string, schema: object): SchemaScanResult;

249

250

/**

251

* Result of schema scanning operation

252

*/

253

class SchemaScanResult {

254

constructor(found: any, ref: any);

255

256

/** Found schema ID */

257

id: any;

258

259

/** Schema reference */

260

ref: any;

261

}

262

```

263

264

## Types

265

266

```javascript { .api }

267

/**

268

* JSON Schema definition interface

269

*/

270

interface Schema {

271

$id?: string;

272

id?: string;

273

$schema?: string;

274

$ref?: string;

275

title?: string;

276

description?: string;

277

multipleOf?: number;

278

maximum?: number;

279

exclusiveMaximum?: number | boolean;

280

minimum?: number;

281

exclusiveMinimum?: number | boolean;

282

maxLength?: number;

283

minLength?: number;

284

pattern?: string | RegExp;

285

additionalItems?: boolean | Schema;

286

items?: Schema | Schema[];

287

contains?: Schema;

288

maxItems?: number;

289

minItems?: number;

290

uniqueItems?: boolean;

291

maxProperties?: number;

292

minProperties?: number;

293

required?: string[] | boolean;

294

propertyNames?: boolean | Schema;

295

additionalProperties?: boolean | Schema;

296

definitions?: {[name: string]: Schema};

297

properties?: {[name: string]: Schema};

298

patternProperties?: {[name: string]: Schema};

299

dependencies?: {[name: string]: Schema | string[]};

300

const?: any;

301

enum?: any[];

302

type?: string | string[];

303

format?: string;

304

allOf?: Schema[];

305

anyOf?: Schema[];

306

oneOf?: Schema[];

307

not?: Schema;

308

if?: Schema;

309

then?: Schema;

310

else?: Schema;

311

default?: any;

312

examples?: any[];

313

}

314

315

/**

316

* Validation options for customizing validation behavior

317

*/

318

interface Options {

319

/** Array of schema keywords to skip during validation */

320

skipAttributes?: string[];

321

322

/** Allow unknown schema keywords without throwing errors */

323

allowUnknownAttributes?: boolean;

324

325

/** Pre-validation hook function for property processing */

326

preValidateProperty?: PreValidatePropertyFunction;

327

328

/** Post-validation rewrite function for instance transformation */

329

rewrite?: RewriteFunction;

330

331

/** Base URI for resolving relative schema references */

332

base?: string;

333

334

/** Throw ValidationError on first validation failure */

335

throwError?: boolean;

336

337

/** Treat undefined values as validation failures */

338

required?: boolean;

339

340

/** Throw ValidatorResultError on first validation failure */

341

throwFirst?: boolean;

342

343

/** Throw ValidatorResultError after complete validation */

344

throwAll?: boolean;

345

346

/** Include nested errors from oneOf/anyOf validations */

347

nestedErrors?: boolean;

348

}

349

350

/**

351

* Post-validation rewrite function for transforming validated instances

352

*/

353

interface RewriteFunction {

354

(instance: any, schema: Schema, options: Options, ctx: SchemaContext): any;

355

}

356

357

/**

358

* Pre-validation property processing function

359

*/

360

interface PreValidatePropertyFunction {

361

(instance: any, key: string, schema: Schema, options: Options, ctx: SchemaContext): any;

362

}

363

364

/**

365

* Validation context passed to custom validators and hooks

366

*/

367

interface SchemaContext {

368

/** Current schema being validated */

369

schema: Schema;

370

371

/** Validation options in use */

372

options: Options;

373

374

/** Property path to current validation location */

375

propertyPath: string;

376

377

/** Base URI for schema resolution */

378

base: string;

379

380

/** Available schemas in the validator registry */

381

schemas: {[base: string]: Schema};

382

383

/** Function to create child validation contexts */

384

makeChild: (schema: Schema, key: string) => SchemaContext;

385

}

386

387

/**

388

* Custom format validation function

389

*/

390

interface CustomFormat {

391

(input: any): boolean;

392

}

393

394

/**

395

* Custom validation attribute/keyword function

396

*/

397

interface CustomProperty {

398

(instance: any, schema: Schema, options: Options, ctx: SchemaContext): string|ValidatorResult;

399

}

400

401

/**

402

* Error detail object for ValidationError constructor

403

*/

404

interface ErrorDetail {

405

/** Error message */

406

message: string;

407

408

/** Error name/type */

409

name: string;

410

411

/** Additional error data */

412

argument: string;

413

}

414

```

415

416

## Usage Examples

417

418

### Custom Formats

419

420

```javascript

421

const { Validator } = require('jsonschema');

422

423

// Add global custom format

424

Validator.prototype.customFormats.myFormat = function(input) {

425

return input === 'myFormat';

426

};

427

428

// Add instance-specific custom format

429

const validator = new Validator();

430

validator.customFormats.phoneNumber = function(input) {

431

return /^\d{3}-\d{3}-\d{4}$/.test(input);

432

};

433

434

const result = validator.validate('555-123-4567', {

435

type: 'string',

436

format: 'phoneNumber'

437

});

438

```

439

440

### Custom Keywords

441

442

```javascript

443

const { Validator } = require('jsonschema');

444

445

const validator = new Validator();

446

447

// Add custom validation keyword

448

validator.attributes.contains = function validateContains(instance, schema, options, ctx) {

449

if(typeof instance !== 'string') return;

450

if(typeof schema.contains !== 'string') {

451

throw new Error('"contains" expects a string');

452

}

453

if(instance.indexOf(schema.contains) < 0) {

454

return 'does not contain the string ' + JSON.stringify(schema.contains);

455

}

456

};

457

458

const result = validator.validate("I am an instance", {

459

type: "string",

460

contains: "I am"

461

});

462

```

463

464

### Rewrite Hook

465

466

```javascript

467

const { Validator } = require('jsonschema');

468

469

const schema = {

470

properties: {

471

date: {id: 'http://example.com/date', type: 'string'},

472

},

473

};

474

475

const value = {

476

date: '2020-09-30T23:39:27.060Z',

477

};

478

479

function unmarshall(instance, schema) {

480

if(schema.id === 'http://example.com/date') {

481

return new Date(instance);

482

}

483

return instance;

484

}

485

486

const v = new Validator();

487

const res = v.validate(value, schema, {rewrite: unmarshall});

488

489

// res.instance.date is now a Date object

490

```

491

492

### Error Handling Options

493

494

```javascript

495

const { Validator } = require('jsonschema');

496

497

const validator = new Validator();

498

499

// Throw on first error

500

try {

501

validator.validate("invalid", {type: "number"}, {throwFirst: true});

502

} catch (error) {

503

// error is ValidatorResultError

504

console.log(error.errors);

505

}

506

507

// Include nested errors from oneOf/anyOf

508

const schema = {

509

oneOf: [

510

{ type: 'string', minLength: 32, maxLength: 32 },

511

{ type: 'string', maxLength: 16 },

512

{ type: 'number' },

513

]

514

};

515

516

const result = validator.validate('This string is 28 chars long', schema, {

517

nestedErrors: true

518

});

519

```