Validators¶
A validator is a callable for model field that takes a value and raises a ValidationError if it doesn’t meet some criteria.
Usage¶
You can pass a list of validators to Field parameter validators:
class ValidatorModel(Model):
regex = fields.CharField(max_length=100, null=True, validators=[RegexValidator("abc.+", re.I)])
# oh no, this will raise ValidationError!
await ValidatorModel.create(regex="ccc")
# this is great!
await ValidatorModel.create(regex="abcd")
Built-in Validators¶
Here is the list of built-in validators:
-
class tortoise.validators.CommaSeparatedIntegerListValidator(allow_negative=
False)[source]¶ A validator to validate whether the given value is valid comma separated integer list or not.
-
class tortoise.validators.DomainNameValidator(accept_idna=
True)[source]¶ Validator for domain names.
Validates domain names according to RFC 1034 and RFC 1123. Supports both ASCII domain names and internationalized domain names (IDN) when accept_idna is True.
- Parameters:¶
- accept_idna=
True¶ If True, accepts internationalized domain names (IDN). Defaults to True.
- accept_idna=
- Raises:¶
InvalidDomainName – if the value is not a valid domain name.
-
ASCII_ONLY_DOMAIN_REGEX =
'(?:\\.(?!-)[a-zA-Z0-9-]{1,63}(?<!-))*'¶
-
ASCII_ONLY_HOSTNAME_REGEX =
'[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?'¶
-
ASCII_ONLY_TLD_REGEX =
'\\.(?!-)(?:[a-zA-Z0-9-]{2,63})(?<!-)\\.?'¶
-
MAX_DOMAIN_LENGTH =
255¶
-
class tortoise.validators.EmailValidator(allowed_domains=
None)[source]¶ Validator for email addresses.
Validates email addresses according to RFC 3696. Checks both the local part (before @) and domain part (after @). Supports domain allowlisting for restricting to specific domains.
- Parameters:¶
- allowed_domains=
None¶ List of allowed domain names. If provided, only emails from these domains will be accepted.
- allowed_domains=
- Raises:¶
InvalidEmailAddress – if the value is not a valid email address.
-
LITERAL_REGEX =
'\\[([A-F0-9:.]+)\\]\\Z'¶
-
MAX_EMAIL_LENGTH =
320¶
-
USER_REGEX =
'(^[-!#$%&\'*+/=?^_`{}|~0-9A-Z]+(\\.[-!#$%&\'*+/=?^_`{}|~0-9A-Z]+)*\\Z|^"([\\001-\\010\\013\\014\\016-\\037!#-\\[\\]-\\177]|\\\\[\\001-\\011\\013\\014\\016-\\177])*"\\Z)'¶
- class tortoise.validators.MaxLengthValidator(max_length)[source]¶
A validator to validate the length of given value whether greater than max_length or not.
- class tortoise.validators.MaxValueValidator(max_value)[source]¶
Max value validator for FloatField, IntField, SmallIntField, BigIntField
- class tortoise.validators.MinLengthValidator(min_length)[source]¶
A validator to validate the length of given value whether less than min_length or not.
- class tortoise.validators.MinValueValidator(min_value)[source]¶
Min value validator for FloatField, IntField, SmallIntField, BigIntField
- class tortoise.validators.NumericValidator[source]¶
-
types =
(<class 'int'>, <class 'float'>, <class 'decimal.Decimal'>)¶
-
types =
- class tortoise.validators.RegexValidator(pattern, flags)[source]¶
A validator to validate the given value whether match regex or not.
-
class tortoise.validators.URLValidator(allowed_schemes=
None)[source]¶ Validator for URLs.
Validates URLs according to RFC 3986. Checks scheme, host, port, and path components. Supports HTTP, HTTPS, FTP, and FTPS schemes by default.
- Parameters:¶
- allowed_schemes=
None¶ List of allowed URL schemes. Defaults to [“http”, “https”, “ftp”, “ftps”].
- allowed_schemes=
- Raises:¶
InvalidURL – if the value is not a valid URL.
InvalidScheme – if the URL scheme is not in the allowed list.
-
ADVANCED_IPV6_REGEX =
'^\\[(.+)\\](?::[0-9]{1,5})?$'¶
-
HOST_REGEX =
'([a-z¡-\uffff0-9](?:[a-z¡-\uffff0-9-]{0,61}[a-z¡-\uffff0-9])?(?:\\.(?!-)[a-z¡-\uffff0-9-]{1,63}(?<!-))*\\.(?!-)(?:[a-z¡-\uffff-]{2,63}|xn--[a-z0-9]{1,59})(?<!-)\\.?|localhost)'¶
-
IPV4_REGEX =
'(?:0|25[0-5]|2[0-4][0-9]|1[0-9]?[0-9]?|[1-9][0-9]?)(?:\\.(?:0|25[0-5]|2[0-4][0-9]|1[0-9]?[0-9]?|[1-9][0-9]?)){3}'¶
-
MAX_HOSTNAME_LENGTH =
253¶
-
MAX_URL_LENGTH =
2048¶
-
SIMPLE_IPV6_REGEX =
'\\[[0-9a-f:.]+\\]'¶
-
UNSAFE_CHARS =
frozenset({'\t', '\n', '\r'})¶
-
URL_REGEX =
'^(?:[a-z0-9.+-]*)://(?:[^\\s:@/]+(?::[^\\s:@/]*)?@)?(?:(?:0|25[0-5]|2[0-4][0-9]|1[0-9]?[0-9]?|[1-9][0-9]?)(?:\\.(?:0|25[0-5]|2[0-4][0-9]|1[0-9]?[0-9]?|[1-9][0-9]?)){3}|\\[[0-9a-f:.]+\\]|([a-z¡-\uffff0-9](?:[a-z¡-\uffff0-9-]{0,61}[a-z¡-\uffff0-9])?(?:\\.(?!-)[a-z¡-\uffff0-9-]{1,63}(?<!-))*\\.(?!-)(?:[a-z¡-\uffff-]{2,63}|xn--[a-z0-9]{1,59})(?<!-)\\.?|localhost))(?::[0-9]{1,5})?(?:[/?#][^\\s]*)?\\Z'¶
- tortoise.validators.validate_ipv46_address(value)[source]¶
A validator to validate whether the given value is valid IPv4Address or IPv6Address or not.
- Raises:¶
ValidationError – if value is invalid IPv4Address or IPv6Address.
- Return type:¶
None
- tortoise.validators.validate_ipv4_address(value)[source]¶
A validator to validate whether the given value is valid IPv4Address or not.
- Raises:¶
ValidationError – if value is invalid IPv4Address.
- Return type:¶
None
- tortoise.validators.validate_ipv6_address(value)[source]¶
A validator to validate whether the given value is valid IPv6Address or not.
- Raises:¶
ValidationError – if value is invalid IPv6Address.
- Return type:¶
None
Custom Validator¶
There are two methods to write a custom validator, one you can write a function by passing a given value, another you can inherit tortoise.validators.Validator and implement __call__.
Here is a example to write a custom validator to validate the given value is an even number:
from tortoise.validators import Validator
from tortoise.exceptions import ValidationError
class EvenNumberValidator(Validator):
"""
A validator to validate whether the given value is an even number or not.
"""
def __call__(self, value: int):
if value % 2 != 0:
raise ValidationError(f"Value '{value}' is not an even number")
# or use function instead of class
def validate_even_number(value:int):
if value % 2 != 0:
raise ValidationError(f"Value '{value}' is not an even number")