or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

Files

docs

error-handling.mdformat-validation.mdindex.mdschema-management.mdvalidation.md

validation.mddocs/

0

# Validation

1

2

Core validation functionality for validating JSON data against JSON Schema specifications, with support for both synchronous and asynchronous validation modes.

3

4

## Capabilities

5

6

### Constructor

7

8

Creates a new validator instance with optional configuration.

9

10

```javascript { .api }

11

/**

12

* Create a new z-schema validator instance

13

* @param options - Configuration options for validation behavior

14

*/

15

constructor(options?: ZSchema.Options);

16

```

17

18

**Usage Examples:**

19

20

```javascript

21

const ZSchema = require("z-schema");

22

23

// Default validator

24

const validator = new ZSchema();

25

26

// Strict mode validator

27

const strictValidator = new ZSchema({

28

strictMode: true,

29

breakOnFirstError: true

30

});

31

32

// Custom configuration

33

const customValidator = new ZSchema({

34

asyncTimeout: 5000,

35

noEmptyStrings: true,

36

reportPathAsArray: true

37

});

38

```

39

40

### Primary Validation

41

42

Validates JSON data against a schema with support for both sync and async modes.

43

44

```javascript { .api }

45

/**

46

* Validate JSON data against a schema

47

* @param json - Data to validate

48

* @param schema - JSON schema to validate against

49

* @param options - Optional validation options

50

* @param callback - Optional callback for async validation

51

* @returns boolean (sync mode) or void (async mode)

52

*/

53

validate(

54

json: any,

55

schema: any,

56

options?: ValidateOptions,

57

callback?: (err: any, valid: boolean) => void

58

): boolean | void;

59

60

interface ValidateOptions {

61

schemaPath?: string;

62

includeErrors?: string[];

63

}

64

```

65

66

**Usage Examples:**

67

68

```javascript

69

const validator = new ZSchema();

70

71

// Synchronous validation

72

const schema = {

73

type: "object",

74

properties: {

75

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

76

age: { type: "number", minimum: 0 }

77

},

78

required: ["name", "age"]

79

};

80

81

const data = { name: "Alice", age: 25 };

82

const valid = validator.validate(data, schema);

83

84

if (!valid) {

85

console.log(validator.getLastErrors());

86

}

87

88

// Asynchronous validation (required for schemas with async format validators)

89

validator.validate(data, schema, function(err, valid) {

90

if (err) {

91

console.error("Validation error:", err);

92

} else if (!valid) {

93

console.log("Validation failed:", validator.getLastErrors());

94

} else {

95

console.log("Validation passed");

96

}

97

});

98

99

// Validation with schema path (validate against subschema)

100

const complexSchema = {

101

definitions: {

102

user: {

103

type: "object",

104

properties: {

105

name: { type: "string" }

106

}

107

}

108

}

109

};

110

111

const valid = validator.validate(

112

{ name: "Bob" },

113

complexSchema,

114

{ schemaPath: "definitions.user" }

115

);

116

117

// Validation with specific error types only

118

const valid = validator.validate(data, schema, {

119

includeErrors: ["INVALID_TYPE", "MINIMUM"]

120

});

121

```

122

123

### Schema Validation

124

125

Validates that a schema itself is a valid JSON Schema.

126

127

```javascript { .api }

128

/**

129

* Validate that a schema is a valid JSON Schema

130

* @param schema - Schema to validate (can be single schema or array)

131

* @returns boolean indicating if schema is valid

132

*/

133

validateSchema(schema: any): boolean;

134

```

135

136

**Usage Examples:**

137

138

```javascript

139

const validator = new ZSchema();

140

141

// Single schema validation

142

const schema = {

143

type: "string",

144

minLength: 5

145

};

146

147

const isValidSchema = validator.validateSchema(schema);

148

if (!isValidSchema) {

149

console.log("Schema validation failed:", validator.getLastErrors());

150

}

151

152

// Multiple schema validation with references

153

const schemas = [

154

{

155

id: "personDetails",

156

type: "object",

157

properties: {

158

firstName: { type: "string" },

159

lastName: { type: "string" }

160

},

161

required: ["firstName", "lastName"]

162

},

163

{

164

id: "addressDetails",

165

type: "object",

166

properties: {

167

street: { type: "string" },

168

city: { type: "string" }

169

},

170

required: ["street", "city"]

171

},

172

{

173

id: "personWithAddress",

174

allOf: [

175

{ $ref: "personDetails" },

176

{ $ref: "addressDetails" }

177

]

178

}

179

];

180

181

const allSchemasValid = validator.validateSchema(schemas);

182

if (allSchemasValid) {

183

// Now validate data against compiled schemas

184

const data = {

185

firstName: "John",

186

lastName: "Doe",

187

street: "123 Main St",

188

city: "Anytown"

189

};

190

191

const valid = validator.validate(data, schemas[2]);

192

}

193

```

194

195

### Schema Compilation

196

197

Compiles a schema for validation without validating it against the meta-schema.

198

199

```javascript { .api }

200

/**

201

* Compile a schema for validation without meta-schema validation

202

* @param schema - Schema to compile

203

* @returns boolean indicating compilation success

204

*/

205

compileSchema(schema: any): boolean;

206

```

207

208

**Usage Examples:**

209

210

```javascript

211

const validator = new ZSchema();

212

213

const schema = {

214

type: "object",

215

properties: {

216

id: { type: "integer" },

217

name: { type: "string" }

218

}

219

};

220

221

// Compile schema (faster than validateSchema)

222

const compiled = validator.compileSchema(schema);

223

if (compiled) {

224

// Schema is ready for validation

225

const valid = validator.validate({ id: 1, name: "test" }, schema);

226

}

227

```

228

229

## Configuration Options

230

231

### Timeout Options

232

233

```javascript { .api }

234

interface TimeoutOptions {

235

/** Timeout in milliseconds for async operations (default: 2000) */

236

asyncTimeout?: number;

237

}

238

```

239

240

### Validation Behavior Options

241

242

```javascript { .api }

243

interface ValidationBehaviorOptions {

244

/** Stop validation after first error (default: false) */

245

breakOnFirstError?: boolean;

246

247

/** Treat empty strings as invalid for string type (default: false) */

248

noEmptyStrings?: boolean;

249

250

/** Treat empty arrays as invalid for array type (default: false) */

251

noEmptyArrays?: boolean;

252

253

/** Require type to be specified in schemas (default: false) */

254

noTypeless?: boolean;

255

256

/** Case insensitive enum value matching (default: false) */

257

enumCaseInsensitiveComparison?: boolean;

258

}

259

```

260

261

### Schema Strictness Options

262

263

```javascript { .api }

264

interface SchemaStrictnessOptions {

265

/** Require additionalProperties/additionalItems to be defined (default: false) */

266

forceAdditional?: boolean;

267

268

/** Assume additionalProperties/Items are false (default: false) */

269

assumeAdditional?: boolean | string[];

270

271

/** Require items to be defined for array schemas (default: false) */

272

forceItems?: boolean;

273

274

/** Require minItems to be defined for array schemas (default: false) */

275

forceMinItems?: boolean;

276

277

/** Require maxItems to be defined for array schemas (default: false) */

278

forceMaxItems?: boolean;

279

280

/** Require minLength to be defined for string schemas (default: false) */

281

forceMinLength?: boolean;

282

283

/** Require maxLength to be defined for string schemas (default: false) */

284

forceMaxLength?: boolean;

285

286

/** Require properties/patternProperties for object schemas (default: false) */

287

forceProperties?: boolean;

288

289

/** Enable multiple strict options at once (default: false) */

290

strictMode?: boolean;

291

}

292

```

293

294

### Advanced Options

295

296

```javascript { .api }

297

interface AdvancedOptions {

298

/** Don't fail on unresolvable remote references (default: false) */

299

ignoreUnresolvableReferences?: boolean;

300

301

/** Reject schemas with unrecognized keywords (default: false) */

302

noExtraKeywords?: boolean;

303

304

/** Require fully RFC3986 compliant URIs (default: false) */

305

strictUris?: boolean;

306

307

/** Don't report unknown formats as errors (default: false) */

308

ignoreUnknownFormats?: boolean;

309

310

/** Report error paths as arrays instead of strings (default: false) */

311

reportPathAsArray?: boolean;

312

313

/** Check schema best practices (default: false) */

314

pedanticCheck?: boolean;

315

316

/** Custom validation function called on every subschema (default: null) */

317

customValidator?: (report: any, schema: any, json: any) => void;

318

}

319

```