0
# Validation Framework
1
2
Field validation system providing built-in validators for common use cases and base classes for custom validators. Validators ensure data integrity at the application level.
3
4
## Capabilities
5
6
### Base Validator
7
8
Abstract base class for creating custom validators.
9
10
```python { .api }
11
from tortoise.validators import Validator
12
13
class Validator(metaclass=abc.ABCMeta):
14
"""Abstract base class for field validators."""
15
16
@abc.abstractmethod
17
def __call__(self, value):
18
"""
19
Validate the given value.
20
21
Args:
22
value: The value to validate
23
24
Raises:
25
ValidationError: If validation fails
26
"""
27
```
28
29
### Text Validators
30
31
Validators for text and string fields.
32
33
```python { .api }
34
from tortoise.validators import RegexValidator, MaxLengthValidator, MinLengthValidator
35
36
class RegexValidator(Validator):
37
"""Validate value matches regular expression pattern."""
38
39
def __init__(self, pattern, flags=0):
40
"""
41
Args:
42
pattern (str): Regular expression pattern
43
flags (int): Regex flags (re.IGNORECASE, etc.)
44
"""
45
46
class MaxLengthValidator(Validator):
47
"""Validate value length does not exceed maximum."""
48
49
def __init__(self, max_length):
50
"""
51
Args:
52
max_length (int): Maximum allowed length
53
"""
54
55
class MinLengthValidator(Validator):
56
"""Validate value length meets minimum requirement."""
57
58
def __init__(self, min_length):
59
"""
60
Args:
61
min_length (int): Minimum required length
62
"""
63
```
64
65
### Numeric Validators
66
67
Validators for numeric fields.
68
69
```python { .api }
70
from tortoise.validators import MinValueValidator, MaxValueValidator
71
72
class MinValueValidator(Validator):
73
"""Validate numeric value meets minimum requirement."""
74
75
def __init__(self, min_value):
76
"""
77
Args:
78
min_value (int|float|Decimal): Minimum allowed value
79
"""
80
81
class MaxValueValidator(Validator):
82
"""Validate numeric value does not exceed maximum."""
83
84
def __init__(self, max_value):
85
"""
86
Args:
87
max_value (int|float|Decimal): Maximum allowed value
88
"""
89
```
90
91
### Specialized Validators
92
93
```python { .api }
94
from tortoise.validators import CommaSeparatedIntegerListValidator
95
96
class CommaSeparatedIntegerListValidator(Validator):
97
"""Validate comma-separated list of integers."""
98
99
def __init__(self, sep=","):
100
"""
101
Args:
102
sep (str): Separator character (default: comma)
103
"""
104
```
105
106
### IP Address Validators
107
108
Validation functions for IP addresses.
109
110
```python { .api }
111
from tortoise.validators import (
112
validate_ipv4_address,
113
validate_ipv6_address,
114
validate_ipv46_address
115
)
116
117
def validate_ipv4_address(value):
118
"""
119
Validate IPv4 address format.
120
121
Args:
122
value (str): IP address string
123
124
Raises:
125
ValidationError: If not valid IPv4 address
126
"""
127
128
def validate_ipv6_address(value):
129
"""
130
Validate IPv6 address format.
131
132
Args:
133
value (str): IP address string
134
135
Raises:
136
ValidationError: If not valid IPv6 address
137
"""
138
139
def validate_ipv46_address(value):
140
"""
141
Validate IPv4 or IPv6 address format.
142
143
Args:
144
value (str): IP address string
145
146
Raises:
147
ValidationError: If not valid IP address
148
"""
149
```
150
151
## Usage Examples
152
153
### Custom Validator
154
155
```python
156
from tortoise.validators import Validator
157
from tortoise.exceptions import ValidationError
158
import re
159
160
class EmailValidator(Validator):
161
"""Validate email address format."""
162
163
def __init__(self):
164
self.pattern = re.compile(r'^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$')
165
166
def __call__(self, value):
167
if not self.pattern.match(value):
168
raise ValidationError(f"'{value}' is not a valid email address")
169
170
# Use in field definition
171
class User(Model):
172
email = CharField(max_length=100, validators=[EmailValidator()])
173
```
174
175
### Built-in Validator Usage
176
177
```python
178
from tortoise.validators import MinLengthValidator, MaxValueValidator
179
from tortoise.models import Model
180
from tortoise.fields import CharField, IntField
181
182
class User(Model):
183
username = CharField(
184
max_length=50,
185
validators=[MinLengthValidator(3)]
186
)
187
age = IntField(
188
validators=[MaxValueValidator(150)]
189
)
190
```
191
192
### Multiple Validators
193
194
```python
195
from tortoise.validators import RegexValidator, MinLengthValidator, MaxLengthValidator
196
197
class Product(Model):
198
code = CharField(
199
max_length=20,
200
validators=[
201
MinLengthValidator(5),
202
MaxLengthValidator(20),
203
RegexValidator(r'^[A-Z0-9-]+$', message="Must contain only uppercase letters, numbers, and hyphens")
204
]
205
)
206
```
207
208
### IP Address Validation
209
210
```python
211
from tortoise.validators import validate_ipv4_address
212
from tortoise.fields import CharField
213
214
class Server(Model):
215
ip_address = CharField(
216
max_length=15,
217
validators=[validate_ipv4_address]
218
)
219
```
220
221
## Validation Process
222
223
1. **Field-level validation**: Validators run when field values are set
224
2. **Model validation**: All field validators run before saving
225
3. **Exception handling**: ValidationError raised for invalid values
226
4. **Custom messages**: Validators can provide custom error messages
227
228
Validators are executed in the order they are defined in the field's validators list.