or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

Files

docs

core-validation.mderror-handling.mdformat-validation.mdindex.mdtype-checking.mdvalidator-creation.mdvalidators.md

validators.mddocs/

0

# Validator Classes

1

2

Draft-specific validator implementations providing full compliance with each JSON Schema specification version. Each validator class implements the complete validation logic for its corresponding JSON Schema draft.

3

4

## Capabilities

5

6

### Draft 2020-12 Validator

7

8

The most recent JSON Schema specification with full support for modern schema features.

9

10

```python { .api }

11

class Draft202012Validator:

12

"""

13

Validator for JSON Schema Draft 2020-12.

14

15

Attributes:

16

- META_SCHEMA: The meta-schema for Draft 2020-12

17

- VALIDATORS: Mapping of validation keywords to functions

18

- TYPE_CHECKER: Type checker for this draft

19

- FORMAT_CHECKER: Format checker for this draft

20

"""

21

22

def __init__(self, schema, registry=None, resolver=None, format_checker=None):

23

"""

24

Initialize validator with schema.

25

26

Parameters:

27

- schema: The schema to validate against (dict or bool)

28

- registry: Schema registry for reference resolution

29

- resolver: Deprecated, use registry instead

30

- format_checker: FormatChecker for format validation

31

"""

32

33

def validate(self, instance):

34

"""

35

Validate instance against schema.

36

37

Parameters:

38

- instance: Data to validate

39

40

Raises:

41

- ValidationError: If validation fails

42

"""

43

44

def is_valid(self, instance):

45

"""

46

Check if instance is valid.

47

48

Parameters:

49

- instance: Data to validate

50

51

Returns:

52

- bool: True if valid, False otherwise

53

"""

54

55

def iter_errors(self, instance):

56

"""

57

Lazily yield validation errors.

58

59

Parameters:

60

- instance: Data to validate

61

62

Yields:

63

- ValidationError: Each validation error found

64

"""

65

66

def evolve(self, **kwargs):

67

"""

68

Create new validator with modified attributes.

69

70

Parameters:

71

- schema: New schema (optional)

72

- format_checker: New format checker (optional)

73

- registry: New registry (optional)

74

75

Returns:

76

- Validator: New validator instance

77

"""

78

79

@classmethod

80

def check_schema(cls, schema):

81

"""

82

Validate schema against meta-schema.

83

84

Parameters:

85

- schema: Schema to validate

86

87

Raises:

88

- SchemaError: If schema is invalid

89

"""

90

91

def is_type(self, instance, type):

92

"""

93

Check if instance is of given JSON Schema type.

94

95

Parameters:

96

- instance: Value to check

97

- type: JSON Schema type name

98

99

Returns:

100

- bool: True if instance is of the type

101

102

Raises:

103

- UnknownType: If type is unknown

104

"""

105

```

106

107

### Draft 2019-09 Validator

108

109

JSON Schema Draft 2019-09 validator with support for unevaluated properties and items.

110

111

```python { .api }

112

class Draft201909Validator:

113

"""Validator for JSON Schema Draft 2019-09."""

114

# Same interface as Draft202012Validator

115

```

116

117

### Draft 7 Validator

118

119

Widely adopted JSON Schema Draft 7 validator with if/then/else support.

120

121

```python { .api }

122

class Draft7Validator:

123

"""Validator for JSON Schema Draft 7."""

124

# Same interface as Draft202012Validator

125

```

126

127

### Draft 6 Validator

128

129

JSON Schema Draft 6 validator with const keyword support.

130

131

```python { .api }

132

class Draft6Validator:

133

"""Validator for JSON Schema Draft 6."""

134

# Same interface as Draft202012Validator

135

```

136

137

### Draft 4 Validator

138

139

Popular JSON Schema Draft 4 validator widely used in many applications.

140

141

```python { .api }

142

class Draft4Validator:

143

"""Validator for JSON Schema Draft 4."""

144

# Same interface as Draft202012Validator

145

```

146

147

### Draft 3 Validator

148

149

Legacy JSON Schema Draft 3 validator for backward compatibility.

150

151

```python { .api }

152

class Draft3Validator:

153

"""Validator for JSON Schema Draft 3."""

154

# Same interface as Draft202012Validator

155

```

156

157

## Usage Examples

158

159

### Basic Validator Usage

160

161

```python

162

from jsonschema import Draft202012Validator, ValidationError

163

164

schema = {

165

"type": "object",

166

"properties": {

167

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

168

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

169

},

170

"required": ["name"]

171

}

172

173

validator = Draft202012Validator(schema)

174

175

# Valid data

176

data = {"name": "Alice", "age": 30}

177

try:

178

validator.validate(data)

179

print("Valid!")

180

except ValidationError as e:

181

print(f"Invalid: {e.message}")

182

183

# Check validity without exception

184

if validator.is_valid(data):

185

print("Data is valid")

186

187

# Get all errors

188

invalid_data = {"age": -5} # Missing required 'name', invalid age

189

errors = list(validator.iter_errors(invalid_data))

190

for error in errors:

191

print(f"Error: {error.message} at path: {'.'.join(str(p) for p in error.path)}")

192

```

193

194

### Schema Version Detection

195

196

```python

197

from jsonschema import validator_for

198

199

# Schema with explicit version

200

schema_v7 = {

201

"$schema": "http://json-schema.org/draft-07/schema#",

202

"type": "string"

203

}

204

205

ValidatorClass = validator_for(schema_v7)

206

print(ValidatorClass.__name__) # Draft7Validator

207

208

# Use detected validator

209

validator = ValidatorClass(schema_v7)

210

validator.validate("hello") # Valid string

211

```

212

213

### Format Validation

214

215

```python

216

from jsonschema import Draft202012Validator, FormatChecker

217

218

schema = {

219

"type": "object",

220

"properties": {

221

"email": {"type": "string", "format": "email"},

222

"date": {"type": "string", "format": "date"}

223

}

224

}

225

226

format_checker = FormatChecker()

227

validator = Draft202012Validator(schema, format_checker=format_checker)

228

229

# Valid with format checking

230

valid_data = {

231

"email": "user@example.com",

232

"date": "2023-12-25"

233

}

234

validator.validate(valid_data) # Passes

235

236

# Invalid format

237

invalid_data = {

238

"email": "not-an-email",

239

"date": "invalid-date"

240

}

241

try:

242

validator.validate(invalid_data)

243

except ValidationError as e:

244

print(f"Format error: {e.message}")

245

```

246

247

### Validator Evolution

248

249

```python

250

from jsonschema import Draft202012Validator, FormatChecker

251

252

# Base validator

253

base_validator = Draft202012Validator({"type": "string"})

254

255

# Create new validator with different schema

256

new_validator = base_validator.evolve(

257

schema={"type": "number", "minimum": 0}

258

)

259

260

# Create validator with format checking

261

format_validator = base_validator.evolve(

262

format_checker=FormatChecker()

263

)

264

```