universal-validator 1.0.0__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
|
@@ -0,0 +1,432 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: universal-validator
|
|
3
|
+
Version: 1.0.0
|
|
4
|
+
Summary: Comprehensive data validation library for API, database, and form contexts
|
|
5
|
+
Home-page: https://github.com/parthivrawat/universal-validator
|
|
6
|
+
Author: Parthiv Rawat
|
|
7
|
+
License: MIT
|
|
8
|
+
Classifier: Development Status :: 4 - Beta
|
|
9
|
+
Classifier: Intended Audience :: Developers
|
|
10
|
+
Classifier: Topic :: Software Development :: Libraries :: Python Modules
|
|
11
|
+
Classifier: License :: OSI Approved :: MIT License
|
|
12
|
+
Classifier: Programming Language :: Python :: 3
|
|
13
|
+
Classifier: Programming Language :: Python :: 3.7
|
|
14
|
+
Classifier: Programming Language :: Python :: 3.8
|
|
15
|
+
Classifier: Programming Language :: Python :: 3.9
|
|
16
|
+
Classifier: Programming Language :: Python :: 3.10
|
|
17
|
+
Classifier: Programming Language :: Python :: 3.11
|
|
18
|
+
Classifier: Programming Language :: Python :: 3.12
|
|
19
|
+
Requires-Python: >=3.7
|
|
20
|
+
Description-Content-Type: text/markdown
|
|
21
|
+
License-File: LICENSE
|
|
22
|
+
Provides-Extra: dev
|
|
23
|
+
Requires-Dist: pytest>=7.0.0; extra == "dev"
|
|
24
|
+
Requires-Dist: pytest-cov>=4.0.0; extra == "dev"
|
|
25
|
+
Dynamic: author
|
|
26
|
+
Dynamic: classifier
|
|
27
|
+
Dynamic: description
|
|
28
|
+
Dynamic: description-content-type
|
|
29
|
+
Dynamic: home-page
|
|
30
|
+
Dynamic: license
|
|
31
|
+
Dynamic: license-file
|
|
32
|
+
Dynamic: provides-extra
|
|
33
|
+
Dynamic: requires-python
|
|
34
|
+
Dynamic: summary
|
|
35
|
+
|
|
36
|
+
# Universal Data Validator
|
|
37
|
+
|
|
38
|
+
A comprehensive data validation library for Python that works across API, database, and form contexts.
|
|
39
|
+
|
|
40
|
+
## Features
|
|
41
|
+
|
|
42
|
+
- ✅ **Rich Validator Types**: String, int, float, bool, email, URL, list, dict
|
|
43
|
+
- ✅ **Schema-Based Validation**: Define complex data structures
|
|
44
|
+
- ✅ **Custom Validators**: Add your own validation logic
|
|
45
|
+
- ✅ **Nested Validation**: Validate nested objects and lists
|
|
46
|
+
- ✅ **Clear Error Messages**: Detailed error reporting with field paths
|
|
47
|
+
- ✅ **Zero Dependencies**: No external dependencies required
|
|
48
|
+
- ✅ **Production Ready**: Comprehensive test coverage
|
|
49
|
+
|
|
50
|
+
## Installation
|
|
51
|
+
|
|
52
|
+
```bash
|
|
53
|
+
pip install universal-validator
|
|
54
|
+
```
|
|
55
|
+
|
|
56
|
+
## Quick Start
|
|
57
|
+
|
|
58
|
+
```python
|
|
59
|
+
from universal_validator import Schema, validators
|
|
60
|
+
|
|
61
|
+
schema = Schema({
|
|
62
|
+
'email': validators.email(),
|
|
63
|
+
'age': validators.int(min_value=0, max_value=120),
|
|
64
|
+
'username': validators.string(min_length=3, max_length=20),
|
|
65
|
+
'tags': validators.list(validators.string())
|
|
66
|
+
})
|
|
67
|
+
|
|
68
|
+
result = schema.validate(data)
|
|
69
|
+
if not result.valid:
|
|
70
|
+
for error in result.errors:
|
|
71
|
+
print(f"{error.field}: {error.message}")
|
|
72
|
+
```
|
|
73
|
+
|
|
74
|
+
## Usage Examples
|
|
75
|
+
|
|
76
|
+
### String Validation
|
|
77
|
+
|
|
78
|
+
```python
|
|
79
|
+
from universal_validator import validators
|
|
80
|
+
|
|
81
|
+
# Basic string
|
|
82
|
+
validator = validators.string()
|
|
83
|
+
|
|
84
|
+
# String with length constraints
|
|
85
|
+
validator = validators.string(min_length=3, max_length=20)
|
|
86
|
+
|
|
87
|
+
# String with pattern
|
|
88
|
+
validator = validators.string(pattern=r'^\d{3}-\d{4}$')
|
|
89
|
+
|
|
90
|
+
# String with choices
|
|
91
|
+
validator = validators.string(choices=['red', 'green', 'blue'])
|
|
92
|
+
|
|
93
|
+
# Optional string
|
|
94
|
+
validator = validators.string(required=False)
|
|
95
|
+
|
|
96
|
+
# Nullable string
|
|
97
|
+
validator = validators.string(nullable=True)
|
|
98
|
+
```
|
|
99
|
+
|
|
100
|
+
### Integer and Float Validation
|
|
101
|
+
|
|
102
|
+
```python
|
|
103
|
+
# Integer with range
|
|
104
|
+
age_validator = validators.int(min_value=0, max_value=120)
|
|
105
|
+
|
|
106
|
+
# Float with range
|
|
107
|
+
price_validator = validators.float(min_value=0.0, max_value=9999.99)
|
|
108
|
+
|
|
109
|
+
# Optional integer
|
|
110
|
+
count_validator = validators.int(required=False)
|
|
111
|
+
```
|
|
112
|
+
|
|
113
|
+
### Boolean Validation
|
|
114
|
+
|
|
115
|
+
```python
|
|
116
|
+
# Boolean
|
|
117
|
+
terms_validator = validators.bool()
|
|
118
|
+
|
|
119
|
+
# Optional boolean
|
|
120
|
+
newsletter_validator = validators.bool(required=False)
|
|
121
|
+
```
|
|
122
|
+
|
|
123
|
+
### Email and URL Validation
|
|
124
|
+
|
|
125
|
+
```python
|
|
126
|
+
# Email validation
|
|
127
|
+
email_validator = validators.email()
|
|
128
|
+
|
|
129
|
+
# URL validation
|
|
130
|
+
url_validator = validators.url()
|
|
131
|
+
```
|
|
132
|
+
|
|
133
|
+
### List Validation
|
|
134
|
+
|
|
135
|
+
```python
|
|
136
|
+
# Simple list
|
|
137
|
+
tags_validator = validators.list()
|
|
138
|
+
|
|
139
|
+
# List with item validation
|
|
140
|
+
numbers_validator = validators.list(validators.int())
|
|
141
|
+
|
|
142
|
+
# List with length constraints
|
|
143
|
+
items_validator = validators.list(
|
|
144
|
+
validators.string(),
|
|
145
|
+
min_length=1,
|
|
146
|
+
max_length=10
|
|
147
|
+
)
|
|
148
|
+
```
|
|
149
|
+
|
|
150
|
+
### Dictionary Validation
|
|
151
|
+
|
|
152
|
+
```python
|
|
153
|
+
# Dictionary with schema
|
|
154
|
+
address_validator = validators.dict({
|
|
155
|
+
'street': validators.string(),
|
|
156
|
+
'city': validators.string(),
|
|
157
|
+
'zip': validators.string(pattern=r'^\d{5}$')
|
|
158
|
+
})
|
|
159
|
+
|
|
160
|
+
# Nested dictionary
|
|
161
|
+
user_validator = validators.dict({
|
|
162
|
+
'name': validators.string(),
|
|
163
|
+
'email': validators.email(),
|
|
164
|
+
'address': validators.dict({
|
|
165
|
+
'street': validators.string(),
|
|
166
|
+
'city': validators.string()
|
|
167
|
+
})
|
|
168
|
+
})
|
|
169
|
+
```
|
|
170
|
+
|
|
171
|
+
### Schema Validation
|
|
172
|
+
|
|
173
|
+
```python
|
|
174
|
+
from universal_validator import Schema, validators
|
|
175
|
+
|
|
176
|
+
# Define schema
|
|
177
|
+
user_schema = Schema({
|
|
178
|
+
'username': validators.string(min_length=3, max_length=20),
|
|
179
|
+
'email': validators.email(),
|
|
180
|
+
'age': validators.int(min_value=13, required=False),
|
|
181
|
+
'bio': validators.string(max_length=500, required=False),
|
|
182
|
+
'tags': validators.list(validators.string()),
|
|
183
|
+
'settings': validators.dict({
|
|
184
|
+
'theme': validators.string(choices=['light', 'dark']),
|
|
185
|
+
'notifications': validators.bool()
|
|
186
|
+
})
|
|
187
|
+
})
|
|
188
|
+
|
|
189
|
+
# Validate data
|
|
190
|
+
data = {
|
|
191
|
+
'username': 'john_doe',
|
|
192
|
+
'email': 'john@example.com',
|
|
193
|
+
'age': 25,
|
|
194
|
+
'tags': ['python', 'javascript'],
|
|
195
|
+
'settings': {
|
|
196
|
+
'theme': 'dark',
|
|
197
|
+
'notifications': True
|
|
198
|
+
}
|
|
199
|
+
}
|
|
200
|
+
|
|
201
|
+
result = user_schema.validate(data)
|
|
202
|
+
|
|
203
|
+
if result.valid:
|
|
204
|
+
print("✅ Data is valid!")
|
|
205
|
+
else:
|
|
206
|
+
print("❌ Validation errors:")
|
|
207
|
+
for error in result.errors:
|
|
208
|
+
print(f" {error.field}: {error.message}")
|
|
209
|
+
```
|
|
210
|
+
|
|
211
|
+
### Custom Validators
|
|
212
|
+
|
|
213
|
+
```python
|
|
214
|
+
from universal_validator import validators
|
|
215
|
+
|
|
216
|
+
def is_even(value):
|
|
217
|
+
"""Custom validator to check if number is even."""
|
|
218
|
+
if value % 2 != 0:
|
|
219
|
+
return "Value must be even"
|
|
220
|
+
return None
|
|
221
|
+
|
|
222
|
+
# Add custom validator
|
|
223
|
+
validator = validators.int().custom(is_even)
|
|
224
|
+
|
|
225
|
+
result = validator.validate(4, 'number')
|
|
226
|
+
print(result.valid) # True
|
|
227
|
+
|
|
228
|
+
result = validator.validate(3, 'number')
|
|
229
|
+
print(result.valid) # False
|
|
230
|
+
print(result.errors[0].message) # "Value must be even"
|
|
231
|
+
```
|
|
232
|
+
|
|
233
|
+
### Multiple Custom Validators
|
|
234
|
+
|
|
235
|
+
```python
|
|
236
|
+
def is_positive(value):
|
|
237
|
+
return "Must be positive" if value <= 0 else None
|
|
238
|
+
|
|
239
|
+
def is_even(value):
|
|
240
|
+
return "Must be even" if value % 2 != 0 else None
|
|
241
|
+
|
|
242
|
+
validator = validators.int().custom(is_positive).custom(is_even)
|
|
243
|
+
|
|
244
|
+
result = validator.validate(4, 'field')
|
|
245
|
+
print(result.valid) # True
|
|
246
|
+
|
|
247
|
+
result = validator.validate(-2, 'field')
|
|
248
|
+
print(result.valid) # False
|
|
249
|
+
```
|
|
250
|
+
|
|
251
|
+
## Real-World Examples
|
|
252
|
+
|
|
253
|
+
### User Registration
|
|
254
|
+
|
|
255
|
+
```python
|
|
256
|
+
from universal_validator import Schema, validators
|
|
257
|
+
|
|
258
|
+
registration_schema = Schema({
|
|
259
|
+
'username': validators.string(min_length=3, max_length=20),
|
|
260
|
+
'email': validators.email(),
|
|
261
|
+
'password': validators.string(min_length=8),
|
|
262
|
+
'confirm_password': validators.string(min_length=8),
|
|
263
|
+
'age': validators.int(min_value=13, required=False),
|
|
264
|
+
'terms_accepted': validators.bool()
|
|
265
|
+
})
|
|
266
|
+
|
|
267
|
+
data = {
|
|
268
|
+
'username': 'john_doe',
|
|
269
|
+
'email': 'john@example.com',
|
|
270
|
+
'password': 'secure_password_123',
|
|
271
|
+
'confirm_password': 'secure_password_123',
|
|
272
|
+
'age': 25,
|
|
273
|
+
'terms_accepted': True
|
|
274
|
+
}
|
|
275
|
+
|
|
276
|
+
result = registration_schema.validate(data)
|
|
277
|
+
```
|
|
278
|
+
|
|
279
|
+
### API Request Validation
|
|
280
|
+
|
|
281
|
+
```python
|
|
282
|
+
api_request_schema = Schema({
|
|
283
|
+
'method': validators.string(choices=['GET', 'POST', 'PUT', 'DELETE']),
|
|
284
|
+
'url': validators.url(),
|
|
285
|
+
'headers': validators.dict(required=False),
|
|
286
|
+
'body': validators.dict(required=False),
|
|
287
|
+
'timeout': validators.float(min_value=0, required=False)
|
|
288
|
+
})
|
|
289
|
+
|
|
290
|
+
request_data = {
|
|
291
|
+
'method': 'POST',
|
|
292
|
+
'url': 'https://api.example.com/users',
|
|
293
|
+
'headers': {'Content-Type': 'application/json'},
|
|
294
|
+
'body': {'name': 'John'},
|
|
295
|
+
'timeout': 30.0
|
|
296
|
+
}
|
|
297
|
+
|
|
298
|
+
result = api_request_schema.validate(request_data)
|
|
299
|
+
```
|
|
300
|
+
|
|
301
|
+
### Configuration Validation
|
|
302
|
+
|
|
303
|
+
```python
|
|
304
|
+
config_schema = Schema({
|
|
305
|
+
'database': validators.dict({
|
|
306
|
+
'host': validators.string(),
|
|
307
|
+
'port': validators.int(min_value=1, max_value=65535),
|
|
308
|
+
'username': validators.string(),
|
|
309
|
+
'password': validators.string(),
|
|
310
|
+
'ssl': validators.bool()
|
|
311
|
+
}),
|
|
312
|
+
'cache': validators.dict({
|
|
313
|
+
'enabled': validators.bool(),
|
|
314
|
+
'ttl': validators.int(min_value=0),
|
|
315
|
+
'max_size': validators.int(min_value=1)
|
|
316
|
+
}),
|
|
317
|
+
'features': validators.list(validators.string())
|
|
318
|
+
})
|
|
319
|
+
|
|
320
|
+
config = {
|
|
321
|
+
'database': {
|
|
322
|
+
'host': 'localhost',
|
|
323
|
+
'port': 5432,
|
|
324
|
+
'username': 'admin',
|
|
325
|
+
'password': 'secret',
|
|
326
|
+
'ssl': True
|
|
327
|
+
},
|
|
328
|
+
'cache': {
|
|
329
|
+
'enabled': True,
|
|
330
|
+
'ttl': 3600,
|
|
331
|
+
'max_size': 1000
|
|
332
|
+
},
|
|
333
|
+
'features': ['feature1', 'feature2']
|
|
334
|
+
}
|
|
335
|
+
|
|
336
|
+
result = config_schema.validate(config)
|
|
337
|
+
```
|
|
338
|
+
|
|
339
|
+
## Error Handling
|
|
340
|
+
|
|
341
|
+
```python
|
|
342
|
+
from universal_validator import Schema, validators, ValidationError
|
|
343
|
+
|
|
344
|
+
schema = Schema({
|
|
345
|
+
'email': validators.email()
|
|
346
|
+
})
|
|
347
|
+
|
|
348
|
+
# Option 1: Check result
|
|
349
|
+
result = schema.validate({'email': 'invalid'})
|
|
350
|
+
if not result.valid:
|
|
351
|
+
for error in result.errors:
|
|
352
|
+
print(f"{error.field}: {error.message}")
|
|
353
|
+
|
|
354
|
+
# Option 2: Raise exception
|
|
355
|
+
try:
|
|
356
|
+
schema.validate_or_raise({'email': 'invalid'})
|
|
357
|
+
except ValidationError as e:
|
|
358
|
+
print(f"Validation failed: {e}")
|
|
359
|
+
```
|
|
360
|
+
|
|
361
|
+
## API Reference
|
|
362
|
+
|
|
363
|
+
### Validators
|
|
364
|
+
|
|
365
|
+
- `validators.string(min_length, max_length, pattern, choices, required, nullable)` - String validator
|
|
366
|
+
- `validators.int(min_value, max_value, required, nullable)` - Integer validator
|
|
367
|
+
- `validators.float(min_value, max_value, required, nullable)` - Float validator
|
|
368
|
+
- `validators.bool(required, nullable)` - Boolean validator
|
|
369
|
+
- `validators.email(required, nullable)` - Email validator
|
|
370
|
+
- `validators.url(required, nullable)` - URL validator
|
|
371
|
+
- `validators.list(item_validator, min_length, max_length, required, nullable)` - List validator
|
|
372
|
+
- `validators.dict(schema, required, nullable)` - Dictionary validator
|
|
373
|
+
|
|
374
|
+
### Schema
|
|
375
|
+
|
|
376
|
+
- `Schema(schema_dict)` - Create a schema
|
|
377
|
+
- `schema.validate(data)` - Validate data and return ValidationResult
|
|
378
|
+
- `schema.validate_or_raise(data)` - Validate data and raise ValidationError if invalid
|
|
379
|
+
|
|
380
|
+
### ValidationResult
|
|
381
|
+
|
|
382
|
+
- `result.valid` - Boolean indicating if validation passed
|
|
383
|
+
- `result.errors` - List of ValidationError objects
|
|
384
|
+
|
|
385
|
+
### ValidationError
|
|
386
|
+
|
|
387
|
+
- `error.field` - Field name that failed validation
|
|
388
|
+
- `error.message` - Error message
|
|
389
|
+
- `error.value` - Value that failed validation
|
|
390
|
+
|
|
391
|
+
## Testing
|
|
392
|
+
|
|
393
|
+
```bash
|
|
394
|
+
# Install dev dependencies
|
|
395
|
+
pip install -e ".[dev]"
|
|
396
|
+
|
|
397
|
+
# Run tests
|
|
398
|
+
pytest test_universal_validator.py -v
|
|
399
|
+
|
|
400
|
+
# Run with coverage
|
|
401
|
+
pytest test_universal_validator.py --cov=universal_validator --cov-report=html
|
|
402
|
+
```
|
|
403
|
+
|
|
404
|
+
## Comparison with Other Libraries
|
|
405
|
+
|
|
406
|
+
| Feature | universal-validator | pydantic | marshmallow | cerberus |
|
|
407
|
+
|---------|-------------------|----------|-------------|----------|
|
|
408
|
+
| Schema-based | ✅ | ✅ | ✅ | ✅ |
|
|
409
|
+
| Custom validators | ✅ | ✅ | ✅ | ✅ |
|
|
410
|
+
| Zero dependencies | ✅ | ❌ | ❌ | ✅ |
|
|
411
|
+
| Nested validation | ✅ | ✅ | ✅ | ✅ |
|
|
412
|
+
| Clear errors | ✅ | ✅ | ✅ | ✅ |
|
|
413
|
+
| Simple API | ✅ | ❌ | ❌ | ✅ |
|
|
414
|
+
| Type hints | ✅ | ✅ | ❌ | ❌ |
|
|
415
|
+
|
|
416
|
+
## License
|
|
417
|
+
|
|
418
|
+
MIT License
|
|
419
|
+
|
|
420
|
+
## Contributing
|
|
421
|
+
|
|
422
|
+
Contributions are welcome! Please feel free to submit a Pull Request.
|
|
423
|
+
|
|
424
|
+
## Changelog
|
|
425
|
+
|
|
426
|
+
### 1.0.0 (2024-01-15)
|
|
427
|
+
- Initial release
|
|
428
|
+
- Support for string, int, float, bool, email, URL, list, dict validators
|
|
429
|
+
- Schema-based validation
|
|
430
|
+
- Custom validators
|
|
431
|
+
- Nested validation
|
|
432
|
+
- Comprehensive test coverage
|
|
@@ -0,0 +1,6 @@
|
|
|
1
|
+
universal_validator.py,sha256=n6rrR6R7HYRilD5McWkWVENKuZ8awOWYtGzW3VpeUCA,15609
|
|
2
|
+
universal_validator-1.0.0.dist-info/licenses/LICENSE,sha256=Qzfvr-Ixz6apkYUiJvtzlRSxx6wTxtrfIns9vuymgLw,1070
|
|
3
|
+
universal_validator-1.0.0.dist-info/METADATA,sha256=rK3rt31ld6yTebboXPrQ79ILIMEV5cMT9GPFHMmI5zs,11371
|
|
4
|
+
universal_validator-1.0.0.dist-info/WHEEL,sha256=YVMoNqKzERt-wjUZwJ33xBGAwnFl-4cqbYkTtWa4itE,91
|
|
5
|
+
universal_validator-1.0.0.dist-info/top_level.txt,sha256=0jky5xjF7BqL6L-K83mH6q_ZNRtQEx6SBGKaGdCNoJI,20
|
|
6
|
+
universal_validator-1.0.0.dist-info/RECORD,,
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2025 Parthiv Rawat
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
universal_validator
|
universal_validator.py
ADDED
|
@@ -0,0 +1,448 @@
|
|
|
1
|
+
"""
|
|
2
|
+
Universal Data Validator Library
|
|
3
|
+
|
|
4
|
+
A comprehensive data validation library that works across API, database, and form contexts.
|
|
5
|
+
|
|
6
|
+
Author: Parthiv Rawat
|
|
7
|
+
License: MIT
|
|
8
|
+
"""
|
|
9
|
+
|
|
10
|
+
from typing import Any, Callable, Dict, List, Optional, Union, Type, TypeVar, Generic
|
|
11
|
+
from dataclasses import dataclass
|
|
12
|
+
from enum import Enum
|
|
13
|
+
import re
|
|
14
|
+
from datetime import datetime
|
|
15
|
+
|
|
16
|
+
|
|
17
|
+
T = TypeVar('T')
|
|
18
|
+
|
|
19
|
+
|
|
20
|
+
class ValidationError(Exception):
|
|
21
|
+
"""Base exception for validation errors."""
|
|
22
|
+
|
|
23
|
+
def __init__(self, field: str, message: str, value: Any = None):
|
|
24
|
+
self.field = field
|
|
25
|
+
self.message = message
|
|
26
|
+
self.value = value
|
|
27
|
+
super().__init__(f"{field}: {message}")
|
|
28
|
+
|
|
29
|
+
|
|
30
|
+
class ValidationResult:
|
|
31
|
+
"""Result of a validation operation."""
|
|
32
|
+
|
|
33
|
+
def __init__(self, valid: bool = True, errors: Optional[List[ValidationError]] = None):
|
|
34
|
+
self.valid = valid
|
|
35
|
+
self.errors = errors or []
|
|
36
|
+
|
|
37
|
+
def add_error(self, error: ValidationError):
|
|
38
|
+
"""Add a validation error."""
|
|
39
|
+
self.valid = False
|
|
40
|
+
self.errors.append(error)
|
|
41
|
+
|
|
42
|
+
def __bool__(self):
|
|
43
|
+
return self.valid
|
|
44
|
+
|
|
45
|
+
def __repr__(self):
|
|
46
|
+
if self.valid:
|
|
47
|
+
return "ValidationResult(valid=True)"
|
|
48
|
+
return f"ValidationResult(valid=False, errors={len(self.errors)})"
|
|
49
|
+
|
|
50
|
+
|
|
51
|
+
class Validator(Generic[T]):
|
|
52
|
+
"""Base validator class."""
|
|
53
|
+
|
|
54
|
+
def __init__(self, required: bool = True, nullable: bool = False):
|
|
55
|
+
self.required = required
|
|
56
|
+
self.nullable = nullable
|
|
57
|
+
self.custom_validators: List[Callable[[Any], Optional[str]]] = []
|
|
58
|
+
|
|
59
|
+
def validate(self, value: Any, field: str = "field") -> ValidationResult:
|
|
60
|
+
"""Validate a value."""
|
|
61
|
+
result = ValidationResult()
|
|
62
|
+
|
|
63
|
+
if value is None:
|
|
64
|
+
if self.required and not self.nullable:
|
|
65
|
+
result.add_error(ValidationError(field, "Field is required"))
|
|
66
|
+
return result
|
|
67
|
+
|
|
68
|
+
type_error = self._validate_type(value, field)
|
|
69
|
+
if type_error:
|
|
70
|
+
result.add_error(type_error)
|
|
71
|
+
return result
|
|
72
|
+
|
|
73
|
+
constraint_errors = self._validate_constraints(value, field)
|
|
74
|
+
for error in constraint_errors:
|
|
75
|
+
result.add_error(error)
|
|
76
|
+
|
|
77
|
+
for custom_validator in self.custom_validators:
|
|
78
|
+
error_msg = custom_validator(value)
|
|
79
|
+
if error_msg:
|
|
80
|
+
result.add_error(ValidationError(field, error_msg, value))
|
|
81
|
+
|
|
82
|
+
return result
|
|
83
|
+
|
|
84
|
+
def _validate_type(self, value: Any, field: str) -> Optional[ValidationError]:
|
|
85
|
+
"""Validate the type of the value."""
|
|
86
|
+
return None
|
|
87
|
+
|
|
88
|
+
def _validate_constraints(self, value: Any, field: str) -> List[ValidationError]:
|
|
89
|
+
"""Validate constraints on the value."""
|
|
90
|
+
return []
|
|
91
|
+
|
|
92
|
+
def custom(self, validator: Callable[[Any], Optional[str]]) -> 'Validator[T]':
|
|
93
|
+
"""Add a custom validator function."""
|
|
94
|
+
self.custom_validators.append(validator)
|
|
95
|
+
return self
|
|
96
|
+
|
|
97
|
+
|
|
98
|
+
class StringValidator(Validator[str]):
|
|
99
|
+
"""Validator for string values."""
|
|
100
|
+
|
|
101
|
+
def __init__(self,
|
|
102
|
+
min_length: Optional[int] = None,
|
|
103
|
+
max_length: Optional[int] = None,
|
|
104
|
+
pattern: Optional[str] = None,
|
|
105
|
+
choices: Optional[List[str]] = None,
|
|
106
|
+
**kwargs):
|
|
107
|
+
super().__init__(**kwargs)
|
|
108
|
+
self.min_length = min_length
|
|
109
|
+
self.max_length = max_length
|
|
110
|
+
self.pattern = pattern
|
|
111
|
+
self.choices = choices
|
|
112
|
+
|
|
113
|
+
def _validate_type(self, value: Any, field: str) -> Optional[ValidationError]:
|
|
114
|
+
if not isinstance(value, str):
|
|
115
|
+
return ValidationError(field, f"Expected string, got {type(value).__name__}", value)
|
|
116
|
+
return None
|
|
117
|
+
|
|
118
|
+
def _validate_constraints(self, value: str, field: str) -> List[ValidationError]:
|
|
119
|
+
errors = []
|
|
120
|
+
|
|
121
|
+
if self.min_length is not None and len(value) < self.min_length:
|
|
122
|
+
errors.append(ValidationError(
|
|
123
|
+
field,
|
|
124
|
+
f"String length must be at least {self.min_length}, got {len(value)}",
|
|
125
|
+
value
|
|
126
|
+
))
|
|
127
|
+
|
|
128
|
+
if self.max_length is not None and len(value) > self.max_length:
|
|
129
|
+
errors.append(ValidationError(
|
|
130
|
+
field,
|
|
131
|
+
f"String length must be at most {self.max_length}, got {len(value)}",
|
|
132
|
+
value
|
|
133
|
+
))
|
|
134
|
+
|
|
135
|
+
if self.pattern is not None and not re.match(self.pattern, value):
|
|
136
|
+
errors.append(ValidationError(
|
|
137
|
+
field,
|
|
138
|
+
f"String does not match pattern {self.pattern}",
|
|
139
|
+
value
|
|
140
|
+
))
|
|
141
|
+
|
|
142
|
+
if self.choices is not None and value not in self.choices:
|
|
143
|
+
errors.append(ValidationError(
|
|
144
|
+
field,
|
|
145
|
+
f"Value must be one of {self.choices}, got '{value}'",
|
|
146
|
+
value
|
|
147
|
+
))
|
|
148
|
+
|
|
149
|
+
return errors
|
|
150
|
+
|
|
151
|
+
|
|
152
|
+
class IntValidator(Validator[int]):
|
|
153
|
+
"""Validator for integer values."""
|
|
154
|
+
|
|
155
|
+
def __init__(self,
|
|
156
|
+
min_value: Optional[int] = None,
|
|
157
|
+
max_value: Optional[int] = None,
|
|
158
|
+
**kwargs):
|
|
159
|
+
super().__init__(**kwargs)
|
|
160
|
+
self.min_value = min_value
|
|
161
|
+
self.max_value = max_value
|
|
162
|
+
|
|
163
|
+
def _validate_type(self, value: Any, field: str) -> Optional[ValidationError]:
|
|
164
|
+
if not isinstance(value, int) or isinstance(value, bool):
|
|
165
|
+
return ValidationError(field, f"Expected int, got {type(value).__name__}", value)
|
|
166
|
+
return None
|
|
167
|
+
|
|
168
|
+
def _validate_constraints(self, value: int, field: str) -> List[ValidationError]:
|
|
169
|
+
errors = []
|
|
170
|
+
|
|
171
|
+
if self.min_value is not None and value < self.min_value:
|
|
172
|
+
errors.append(ValidationError(
|
|
173
|
+
field,
|
|
174
|
+
f"Value must be at least {self.min_value}, got {value}",
|
|
175
|
+
value
|
|
176
|
+
))
|
|
177
|
+
|
|
178
|
+
if self.max_value is not None and value > self.max_value:
|
|
179
|
+
errors.append(ValidationError(
|
|
180
|
+
field,
|
|
181
|
+
f"Value must be at most {self.max_value}, got {value}",
|
|
182
|
+
value
|
|
183
|
+
))
|
|
184
|
+
|
|
185
|
+
return errors
|
|
186
|
+
|
|
187
|
+
|
|
188
|
+
class FloatValidator(Validator[float]):
|
|
189
|
+
"""Validator for float values."""
|
|
190
|
+
|
|
191
|
+
def __init__(self,
|
|
192
|
+
min_value: Optional[float] = None,
|
|
193
|
+
max_value: Optional[float] = None,
|
|
194
|
+
**kwargs):
|
|
195
|
+
super().__init__(**kwargs)
|
|
196
|
+
self.min_value = min_value
|
|
197
|
+
self.max_value = max_value
|
|
198
|
+
|
|
199
|
+
def _validate_type(self, value: Any, field: str) -> Optional[ValidationError]:
|
|
200
|
+
if not isinstance(value, (int, float)) or isinstance(value, bool):
|
|
201
|
+
return ValidationError(field, f"Expected float, got {type(value).__name__}", value)
|
|
202
|
+
return None
|
|
203
|
+
|
|
204
|
+
def _validate_constraints(self, value: float, field: str) -> List[ValidationError]:
|
|
205
|
+
errors = []
|
|
206
|
+
|
|
207
|
+
if self.min_value is not None and value < self.min_value:
|
|
208
|
+
errors.append(ValidationError(
|
|
209
|
+
field,
|
|
210
|
+
f"Value must be at least {self.min_value}, got {value}",
|
|
211
|
+
value
|
|
212
|
+
))
|
|
213
|
+
|
|
214
|
+
if self.max_value is not None and value > self.max_value:
|
|
215
|
+
errors.append(ValidationError(
|
|
216
|
+
field,
|
|
217
|
+
f"Value must be at most {self.max_value}, got {value}",
|
|
218
|
+
value
|
|
219
|
+
))
|
|
220
|
+
|
|
221
|
+
return errors
|
|
222
|
+
|
|
223
|
+
|
|
224
|
+
class BoolValidator(Validator[bool]):
|
|
225
|
+
"""Validator for boolean values."""
|
|
226
|
+
|
|
227
|
+
def _validate_type(self, value: Any, field: str) -> Optional[ValidationError]:
|
|
228
|
+
if not isinstance(value, bool):
|
|
229
|
+
return ValidationError(field, f"Expected bool, got {type(value).__name__}", value)
|
|
230
|
+
return None
|
|
231
|
+
|
|
232
|
+
|
|
233
|
+
class EmailValidator(StringValidator):
|
|
234
|
+
"""Validator for email addresses."""
|
|
235
|
+
|
|
236
|
+
def __init__(self, **kwargs):
|
|
237
|
+
pattern = r'^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$'
|
|
238
|
+
super().__init__(pattern=pattern, **kwargs)
|
|
239
|
+
|
|
240
|
+
def _validate_constraints(self, value: str, field: str) -> List[ValidationError]:
|
|
241
|
+
errors = super()._validate_constraints(value, field)
|
|
242
|
+
|
|
243
|
+
if not re.match(self.pattern, value):
|
|
244
|
+
errors = [ValidationError(field, f"Invalid email address: {value}", value)]
|
|
245
|
+
|
|
246
|
+
return errors
|
|
247
|
+
|
|
248
|
+
|
|
249
|
+
class UrlValidator(StringValidator):
|
|
250
|
+
"""Validator for URLs."""
|
|
251
|
+
|
|
252
|
+
def __init__(self, **kwargs):
|
|
253
|
+
pattern = r'^https?://[^\s/$.?#].[^\s]*$'
|
|
254
|
+
super().__init__(pattern=pattern, **kwargs)
|
|
255
|
+
|
|
256
|
+
def _validate_constraints(self, value: str, field: str) -> List[ValidationError]:
|
|
257
|
+
errors = super()._validate_constraints(value, field)
|
|
258
|
+
|
|
259
|
+
if not re.match(self.pattern, value):
|
|
260
|
+
errors = [ValidationError(field, f"Invalid URL: {value}", value)]
|
|
261
|
+
|
|
262
|
+
return errors
|
|
263
|
+
|
|
264
|
+
|
|
265
|
+
class ListValidator(Validator[List]):
|
|
266
|
+
"""Validator for list values."""
|
|
267
|
+
|
|
268
|
+
def __init__(self,
|
|
269
|
+
item_validator: Optional[Validator] = None,
|
|
270
|
+
min_length: Optional[int] = None,
|
|
271
|
+
max_length: Optional[int] = None,
|
|
272
|
+
**kwargs):
|
|
273
|
+
super().__init__(**kwargs)
|
|
274
|
+
self.item_validator = item_validator
|
|
275
|
+
self.min_length = min_length
|
|
276
|
+
self.max_length = max_length
|
|
277
|
+
|
|
278
|
+
def _validate_type(self, value: Any, field: str) -> Optional[ValidationError]:
|
|
279
|
+
if not isinstance(value, list):
|
|
280
|
+
return ValidationError(field, f"Expected list, got {type(value).__name__}", value)
|
|
281
|
+
return None
|
|
282
|
+
|
|
283
|
+
def _validate_constraints(self, value: List, field: str) -> List[ValidationError]:
|
|
284
|
+
errors = []
|
|
285
|
+
|
|
286
|
+
if self.min_length is not None and len(value) < self.min_length:
|
|
287
|
+
errors.append(ValidationError(
|
|
288
|
+
field,
|
|
289
|
+
f"List length must be at least {self.min_length}, got {len(value)}",
|
|
290
|
+
value
|
|
291
|
+
))
|
|
292
|
+
|
|
293
|
+
if self.max_length is not None and len(value) > self.max_length:
|
|
294
|
+
errors.append(ValidationError(
|
|
295
|
+
field,
|
|
296
|
+
f"List length must be at most {self.max_length}, got {len(value)}",
|
|
297
|
+
value
|
|
298
|
+
))
|
|
299
|
+
|
|
300
|
+
if self.item_validator:
|
|
301
|
+
for i, item in enumerate(value):
|
|
302
|
+
item_result = self.item_validator.validate(item, f"{field}[{i}]")
|
|
303
|
+
errors.extend(item_result.errors)
|
|
304
|
+
|
|
305
|
+
return errors
|
|
306
|
+
|
|
307
|
+
|
|
308
|
+
class DictValidator(Validator[Dict]):
|
|
309
|
+
"""Validator for dictionary values."""
|
|
310
|
+
|
|
311
|
+
def __init__(self,
|
|
312
|
+
schema: Optional[Dict[str, Validator]] = None,
|
|
313
|
+
**kwargs):
|
|
314
|
+
super().__init__(**kwargs)
|
|
315
|
+
self.schema = schema or {}
|
|
316
|
+
|
|
317
|
+
def _validate_type(self, value: Any, field: str) -> Optional[ValidationError]:
|
|
318
|
+
if not isinstance(value, dict):
|
|
319
|
+
return ValidationError(field, f"Expected dict, got {type(value).__name__}", value)
|
|
320
|
+
return None
|
|
321
|
+
|
|
322
|
+
def _validate_constraints(self, value: Dict, field: str) -> List[ValidationError]:
|
|
323
|
+
errors = []
|
|
324
|
+
|
|
325
|
+
for key, validator in self.schema.items():
|
|
326
|
+
if key in value:
|
|
327
|
+
result = validator.validate(value[key], f"{field}.{key}")
|
|
328
|
+
errors.extend(result.errors)
|
|
329
|
+
elif validator.required:
|
|
330
|
+
errors.append(ValidationError(f"{field}.{key}", "Field is required"))
|
|
331
|
+
|
|
332
|
+
return errors
|
|
333
|
+
|
|
334
|
+
|
|
335
|
+
class Schema:
|
|
336
|
+
"""Schema for validating complex data structures."""
|
|
337
|
+
|
|
338
|
+
def __init__(self, schema: Dict[str, Validator]):
|
|
339
|
+
self.schema = schema
|
|
340
|
+
|
|
341
|
+
def validate(self, data: Dict[str, Any]) -> ValidationResult:
|
|
342
|
+
"""Validate data against the schema."""
|
|
343
|
+
result = ValidationResult()
|
|
344
|
+
|
|
345
|
+
if not isinstance(data, dict):
|
|
346
|
+
result.add_error(ValidationError("root", f"Expected dict, got {type(data).__name__}"))
|
|
347
|
+
return result
|
|
348
|
+
|
|
349
|
+
for field, validator in self.schema.items():
|
|
350
|
+
if field in data:
|
|
351
|
+
field_result = validator.validate(data[field], field)
|
|
352
|
+
for error in field_result.errors:
|
|
353
|
+
result.add_error(error)
|
|
354
|
+
elif validator.required:
|
|
355
|
+
result.add_error(ValidationError(field, "Field is required"))
|
|
356
|
+
|
|
357
|
+
return result
|
|
358
|
+
|
|
359
|
+
def validate_or_raise(self, data: Dict[str, Any]) -> None:
|
|
360
|
+
"""Validate data and raise exception if invalid."""
|
|
361
|
+
result = self.validate(data)
|
|
362
|
+
if not result.valid:
|
|
363
|
+
error_messages = [f"{e.field}: {e.message}" for e in result.errors]
|
|
364
|
+
raise ValidationError("validation", "\n".join(error_messages))
|
|
365
|
+
|
|
366
|
+
|
|
367
|
+
class validators:
|
|
368
|
+
"""Namespace for validator factory functions."""
|
|
369
|
+
|
|
370
|
+
@staticmethod
|
|
371
|
+
def string(min_length: Optional[int] = None,
|
|
372
|
+
max_length: Optional[int] = None,
|
|
373
|
+
pattern: Optional[str] = None,
|
|
374
|
+
choices: Optional[List[str]] = None,
|
|
375
|
+
required: bool = True,
|
|
376
|
+
nullable: bool = False) -> StringValidator:
|
|
377
|
+
"""Create a string validator."""
|
|
378
|
+
return StringValidator(
|
|
379
|
+
min_length=min_length,
|
|
380
|
+
max_length=max_length,
|
|
381
|
+
pattern=pattern,
|
|
382
|
+
choices=choices,
|
|
383
|
+
required=required,
|
|
384
|
+
nullable=nullable
|
|
385
|
+
)
|
|
386
|
+
|
|
387
|
+
@staticmethod
|
|
388
|
+
def int(min_value: Optional[int] = None,
|
|
389
|
+
max_value: Optional[int] = None,
|
|
390
|
+
required: bool = True,
|
|
391
|
+
nullable: bool = False) -> IntValidator:
|
|
392
|
+
"""Create an integer validator."""
|
|
393
|
+
return IntValidator(
|
|
394
|
+
min_value=min_value,
|
|
395
|
+
max_value=max_value,
|
|
396
|
+
required=required,
|
|
397
|
+
nullable=nullable
|
|
398
|
+
)
|
|
399
|
+
|
|
400
|
+
@staticmethod
|
|
401
|
+
def float(min_value: Optional[float] = None,
|
|
402
|
+
max_value: Optional[float] = None,
|
|
403
|
+
required: bool = True,
|
|
404
|
+
nullable: bool = False) -> FloatValidator:
|
|
405
|
+
"""Create a float validator."""
|
|
406
|
+
return FloatValidator(
|
|
407
|
+
min_value=min_value,
|
|
408
|
+
max_value=max_value,
|
|
409
|
+
required=required,
|
|
410
|
+
nullable=nullable
|
|
411
|
+
)
|
|
412
|
+
|
|
413
|
+
@staticmethod
|
|
414
|
+
def bool(required: bool = True, nullable: bool = False) -> BoolValidator:
|
|
415
|
+
"""Create a boolean validator."""
|
|
416
|
+
return BoolValidator(required=required, nullable=nullable)
|
|
417
|
+
|
|
418
|
+
@staticmethod
|
|
419
|
+
def email(required: bool = True, nullable: bool = False) -> EmailValidator:
|
|
420
|
+
"""Create an email validator."""
|
|
421
|
+
return EmailValidator(required=required, nullable=nullable)
|
|
422
|
+
|
|
423
|
+
@staticmethod
|
|
424
|
+
def url(required: bool = True, nullable: bool = False) -> UrlValidator:
|
|
425
|
+
"""Create a URL validator."""
|
|
426
|
+
return UrlValidator(required=required, nullable=nullable)
|
|
427
|
+
|
|
428
|
+
@staticmethod
|
|
429
|
+
def list(item_validator: Optional[Validator] = None,
|
|
430
|
+
min_length: Optional[int] = None,
|
|
431
|
+
max_length: Optional[int] = None,
|
|
432
|
+
required: bool = True,
|
|
433
|
+
nullable: bool = False) -> ListValidator:
|
|
434
|
+
"""Create a list validator."""
|
|
435
|
+
return ListValidator(
|
|
436
|
+
item_validator=item_validator,
|
|
437
|
+
min_length=min_length,
|
|
438
|
+
max_length=max_length,
|
|
439
|
+
required=required,
|
|
440
|
+
nullable=nullable
|
|
441
|
+
)
|
|
442
|
+
|
|
443
|
+
@staticmethod
|
|
444
|
+
def dict(schema: Optional[Dict[str, Validator]] = None,
|
|
445
|
+
required: bool = True,
|
|
446
|
+
nullable: bool = False) -> DictValidator:
|
|
447
|
+
"""Create a dictionary validator."""
|
|
448
|
+
return DictValidator(schema=schema, required=required, nullable=nullable)
|