0
# Format Validation
1
2
String format validation system for JSON Schema format keyword validation. This module provides format checkers for common data formats and allows registration of custom format validators.
3
4
## Capabilities
5
6
### Format Checker Class
7
8
Main class for registering and executing format validation functions.
9
10
```python { .api }
11
class FormatChecker:
12
"""Registry for format validation functions."""
13
14
checkers: dict
15
16
def __init__(self, formats: Iterable[str] | None = None) -> None:
17
"""
18
Initialize format checker.
19
20
Args:
21
formats: Specific formats to include (all if None)
22
"""
23
24
def checks(self, format: str, raises: type = FormatError) -> Callable:
25
"""
26
Decorator to register a format checking function.
27
28
Args:
29
format: Format name to register for
30
raises: Exception type to raise on format errors
31
32
Returns:
33
Decorator function
34
"""
35
36
@classmethod
37
def cls_checks(cls, format: str, raises: type = FormatError) -> Callable:
38
"""
39
Class method decorator to register a format checking function.
40
41
Args:
42
format: Format name to register for
43
raises: Exception type to raise on format errors
44
45
Returns:
46
Decorator function
47
"""
48
49
def check(self, instance: Any, format: str) -> None:
50
"""
51
Check if instance conforms to format.
52
53
Args:
54
instance: Value to check
55
format: Format name to validate against
56
57
Raises:
58
FormatError: If format validation fails
59
"""
60
61
def conforms(self, instance: Any, format: str) -> bool:
62
"""
63
Check if instance conforms to format without raising.
64
65
Args:
66
instance: Value to check
67
format: Format name to validate against
68
69
Returns:
70
True if format is valid, False otherwise
71
"""
72
```
73
74
Usage example:
75
76
```python
77
from jsonschema import FormatChecker, ValidationError, Draft7Validator
78
79
# Create custom format checker
80
checker = FormatChecker()
81
82
@checker.checks('positive-int')
83
def check_positive_int(instance):
84
if not isinstance(instance, int) or instance <= 0:
85
raise ValueError("Not a positive integer")
86
return True
87
88
# Use with validator
89
schema = {
90
"type": "integer",
91
"format": "positive-int"
92
}
93
94
validator = Draft7Validator(schema, format_checker=checker)
95
validator.validate(5) # Valid
96
# validator.validate(-1) # Would raise ValidationError
97
```
98
99
### Pre-configured Format Checkers
100
101
Ready-to-use format checkers for different JSON Schema draft versions.
102
103
```python { .api }
104
# Draft-specific format checkers with appropriate format support
105
draft3_format_checker: FormatChecker
106
draft4_format_checker: FormatChecker
107
draft6_format_checker: FormatChecker
108
draft7_format_checker: FormatChecker
109
```
110
111
Usage example:
112
113
```python
114
from jsonschema import Draft7Validator, draft7_format_checker
115
116
schema = {
117
"type": "object",
118
"properties": {
119
"email": {"type": "string", "format": "email"},
120
"website": {"type": "string", "format": "uri"},
121
"created": {"type": "string", "format": "date-time"}
122
}
123
}
124
125
validator = Draft7Validator(schema, format_checker=draft7_format_checker)
126
127
data = {
128
"email": "user@example.com",
129
"website": "https://example.com",
130
"created": "2023-01-01T12:00:00Z"
131
}
132
133
validator.validate(data) # All formats will be validated
134
```
135
136
### Email Format Validation
137
138
Validate email address format.
139
140
```python { .api }
141
def is_email(instance: Any) -> bool:
142
"""
143
Check if instance is a valid email address.
144
145
Args:
146
instance: Value to check
147
148
Returns:
149
True if valid email format, False otherwise
150
"""
151
```
152
153
### URI Format Validation
154
155
Validate URI and URI reference formats.
156
157
```python { .api }
158
def is_uri(instance: Any) -> bool:
159
"""
160
Check if instance is a valid URI.
161
162
Args:
163
instance: Value to check
164
165
Returns:
166
True if valid URI format, False otherwise
167
"""
168
169
def is_uri_reference(instance: Any) -> bool:
170
"""
171
Check if instance is a valid URI reference.
172
173
Args:
174
instance: Value to check
175
176
Returns:
177
True if valid URI reference format, False otherwise
178
"""
179
180
def is_iri(instance: Any) -> bool:
181
"""
182
Check if instance is a valid IRI (Internationalized Resource Identifier).
183
184
Args:
185
instance: Value to check
186
187
Returns:
188
True if valid IRI format, False otherwise
189
"""
190
191
def is_iri_reference(instance: Any) -> bool:
192
"""
193
Check if instance is a valid IRI reference.
194
195
Args:
196
instance: Value to check
197
198
Returns:
199
True if valid IRI reference format, False otherwise
200
"""
201
```
202
203
### IP Address Format Validation
204
205
Validate IPv4 and IPv6 address formats.
206
207
```python { .api }
208
def is_ipv4(instance: Any) -> bool:
209
"""
210
Check if instance is a valid IPv4 address.
211
212
Args:
213
instance: Value to check
214
215
Returns:
216
True if valid IPv4 format, False otherwise
217
"""
218
219
def is_ipv6(instance: Any) -> bool:
220
"""
221
Check if instance is a valid IPv6 address.
222
223
Args:
224
instance: Value to check
225
226
Returns:
227
True if valid IPv6 format, False otherwise
228
"""
229
```
230
231
### Hostname Format Validation
232
233
Validate hostname and internationalized domain name formats.
234
235
```python { .api }
236
def is_host_name(instance: Any) -> bool:
237
"""
238
Check if instance is a valid hostname.
239
240
Args:
241
instance: Value to check
242
243
Returns:
244
True if valid hostname format, False otherwise
245
"""
246
247
def is_idn_host_name(instance: Any) -> bool:
248
"""
249
Check if instance is a valid internationalized domain name.
250
251
Args:
252
instance: Value to check
253
254
Returns:
255
True if valid IDN hostname format, False otherwise
256
"""
257
```
258
259
### Date and Time Format Validation
260
261
Validate date, time, and datetime formats according to RFC 3339.
262
263
```python { .api }
264
def is_datetime(instance: Any) -> bool:
265
"""
266
Check if instance is a valid RFC 3339 datetime.
267
268
Args:
269
instance: Value to check
270
271
Returns:
272
True if valid datetime format, False otherwise
273
"""
274
275
def is_date(instance: Any) -> bool:
276
"""
277
Check if instance is a valid RFC 3339 date.
278
279
Args:
280
instance: Value to check
281
282
Returns:
283
True if valid date format, False otherwise
284
"""
285
286
def is_time(instance: Any) -> bool:
287
"""
288
Check if instance is a valid RFC 3339 time.
289
290
Args:
291
instance: Value to check
292
293
Returns:
294
True if valid time format, False otherwise
295
"""
296
297
def is_draft3_time(instance: Any) -> bool:
298
"""
299
Check if instance is a valid time according to Draft 3 specification.
300
301
Args:
302
instance: Value to check
303
304
Returns:
305
True if valid Draft 3 time format, False otherwise
306
"""
307
```
308
309
### Regular Expression Format Validation
310
311
Validate regular expression format.
312
313
```python { .api }
314
def is_regex(instance: Any) -> bool:
315
"""
316
Check if instance is a valid regular expression.
317
318
Args:
319
instance: Value to check
320
321
Returns:
322
True if valid regex format, False otherwise
323
"""
324
```
325
326
### CSS Color Format Validation
327
328
Validate CSS color formats.
329
330
```python { .api }
331
def is_css_color_code(instance: Any) -> bool:
332
"""
333
Check if instance is a valid CSS color code.
334
335
Args:
336
instance: Value to check
337
338
Returns:
339
True if valid CSS color code, False otherwise
340
"""
341
342
def is_css21_color(instance: Any) -> bool:
343
"""
344
Check if instance is a valid CSS 2.1 color.
345
346
Args:
347
instance: Value to check
348
349
Returns:
350
True if valid CSS 2.1 color, False otherwise
351
"""
352
353
def is_css3_color(instance: Any) -> bool:
354
"""
355
Check if instance is a valid CSS 3 color.
356
357
Args:
358
instance: Value to check
359
360
Returns:
361
True if valid CSS 3 color, False otherwise
362
"""
363
```
364
365
### JSON Pointer Format Validation
366
367
Validate JSON Pointer and relative JSON Pointer formats.
368
369
```python { .api }
370
def is_json_pointer(instance: Any) -> bool:
371
"""
372
Check if instance is a valid JSON Pointer (RFC 6901).
373
374
Args:
375
instance: Value to check
376
377
Returns:
378
True if valid JSON Pointer format, False otherwise
379
"""
380
381
def is_relative_json_pointer(instance: Any) -> bool:
382
"""
383
Check if instance is a valid relative JSON Pointer.
384
385
Args:
386
instance: Value to check
387
388
Returns:
389
True if valid relative JSON Pointer format, False otherwise
390
"""
391
```
392
393
### URI Template Format Validation
394
395
Validate URI template format according to RFC 6570.
396
397
```python { .api }
398
def is_uri_template(instance: Any, template_validator: Callable | None = None) -> bool:
399
"""
400
Check if instance is a valid URI template.
401
402
Args:
403
instance: Value to check
404
template_validator: Custom template validator function
405
406
Returns:
407
True if valid URI template format, False otherwise
408
"""
409
```
410
411
## Usage Examples
412
413
### Basic Format Validation
414
415
```python
416
from jsonschema import Draft7Validator, draft7_format_checker
417
418
# Email validation
419
schema = {"type": "string", "format": "email"}
420
validator = Draft7Validator(schema, format_checker=draft7_format_checker)
421
422
validator.validate("user@example.com") # Valid
423
# validator.validate("invalid-email") # ValidationError
424
425
# Date validation
426
schema = {"type": "string", "format": "date"}
427
validator = Draft7Validator(schema, format_checker=draft7_format_checker)
428
429
validator.validate("2023-12-01") # Valid
430
# validator.validate("invalid-date") # ValidationError
431
```
432
433
### Custom Format Registration
434
435
```python
436
from jsonschema import FormatChecker, Draft7Validator
437
import re
438
439
# Create custom format checker
440
custom_checker = FormatChecker()
441
442
@custom_checker.checks('phone-number')
443
def check_phone_number(instance):
444
pattern = r'^\+?1?-?\.?\s?\(?(\d{3})\)?[\s\-\.]?(\d{3})[\s\-\.]?(\d{4})$'
445
if not re.match(pattern, str(instance)):
446
raise ValueError("Invalid phone number format")
447
return True
448
449
# Use with schema
450
schema = {
451
"type": "object",
452
"properties": {
453
"phone": {"type": "string", "format": "phone-number"}
454
}
455
}
456
457
validator = Draft7Validator(schema, format_checker=custom_checker)
458
validator.validate({"phone": "+1-555-123-4567"}) # Valid
459
```
460
461
### Combining Format Checkers
462
463
```python
464
from jsonschema import FormatChecker, Draft7Validator, draft7_format_checker
465
466
# Extend existing format checker
467
extended_checker = FormatChecker()
468
469
# Add all standard formats
470
for format_name, format_func in draft7_format_checker.checkers.items():
471
extended_checker.checkers[format_name] = format_func
472
473
# Add custom format
474
@extended_checker.checks('custom-id')
475
def check_custom_id(instance):
476
if not isinstance(instance, str) or not instance.startswith('ID-'):
477
raise ValueError("Custom ID must start with 'ID-'")
478
return True
479
480
# Now supports both standard and custom formats
481
schema = {
482
"type": "object",
483
"properties": {
484
"email": {"type": "string", "format": "email"},
485
"id": {"type": "string", "format": "custom-id"}
486
}
487
}
488
489
validator = Draft7Validator(schema, format_checker=extended_checker)
490
validator.validate({"email": "user@example.com", "id": "ID-12345"})
491
```
492
493
## Types
494
495
```python { .api }
496
from typing import Any, Callable, Iterable
497
from jsonschema.exceptions import FormatError
498
```