From 0982069b5d6c979d9f7fb6c519dfac9f8e121a32 Mon Sep 17 00:00:00 2001 From: Jovial Joe Jayarson Date: Tue, 19 Mar 2024 16:40:17 +0500 Subject: [PATCH] Deployed c2d3fb7 to 0.23 with MkDocs 1.5.3 and mike 2.0.0 --- 0.23/_build/man/validators.1 | 1085 +++++++++++++++++++++++++--- 0.23/references/between.rst | 2 + 0.23/references/between/index.html | 64 +- 0.23/references/btc_address.rst | 2 + 0.23/references/card.rst | 2 + 0.23/references/country_code.rst | 2 + 0.23/references/domain.rst | 2 + 0.23/references/email.rst | 2 + 0.23/references/hashes.rst | 2 + 0.23/references/hostname.rst | 2 + 0.23/references/i18n.rst | 2 + 0.23/references/iban.rst | 2 + 0.23/references/ip_address.rst | 2 + 0.23/references/length.rst | 2 + 0.23/references/length/index.html | 65 +- 0.23/references/mac_address.rst | 2 + 0.23/references/slug.rst | 2 + 0.23/references/url.rst | 2 + 0.23/references/utils.rst | 2 + 0.23/references/uuid.rst | 2 + 0.23/search/search_index.json | 2 +- 0.23/sitemap.xml.gz | Bin 335 -> 335 bytes 0.23/validators.1 | 1085 +++++++++++++++++++++++++--- 23 files changed, 2099 insertions(+), 236 deletions(-) diff --git a/0.23/_build/man/validators.1 b/0.23/_build/man/validators.1 index f4e8f61b..8b121ecc 100644 --- a/0.23/_build/man/validators.1 +++ b/0.23/_build/man/validators.1 @@ -27,7 +27,7 @@ level margin: \\n[rst2man-indent\\n[rst2man-indent-level]] .\" new: \\n[rst2man-indent\\n[rst2man-indent-level]] .in \\n[rst2man-indent\\n[rst2man-indent-level]]u .. -.TH "VALIDATORS" "1" "Mar 19, 2024" "0.23.0" "validators" +.TH "VALIDATORS" "1" "Mar 19, 2024" "0.23.1" "validators" .SH NAME validators \- Python Data Validation for Humans™ .sp @@ -120,10 +120,9 @@ If \fIvalue\fP is not in between the given conditions. .B Raises .INDENT 7.0 .IP \(bu 2 -\fBValueError\fP \-\- If both \fImin_val\fP and \fImax_val\fP are \fINone\fP, - or if \fImin_val\fP is greater than \fImax_val\fP\&. +\fB(\fP\fBValueError\fP\fB)\fP \-\- If \fImin_val\fP is greater than \fImax_val\fP\&. .IP \(bu 2 -\fBTypeError\fP \-\- If there\(aqs a type mismatch before comparison. +\fB(\fP\fBTypeError\fP\fB)\fP \-\- If there\(aqs a type mismatch during comparison. .UNINDENT .UNINDENT .sp @@ -134,12 +133,10 @@ If \fIvalue\fP is not in between the given conditions. .IP \(bu 2 \fIPossibleValueTypes\fP = \fITypeVar(\(dqPossibleValueTypes\(dq, int, float, str, datetime)\fP .IP \(bu 2 -Either one of \fImin_val\fP or \fImax_val\fP must be provided. +If neither \fImin_val\fP nor \fImax_val\fP is provided, result will always be \fITrue\fP\&. .UNINDENT .UNINDENT .UNINDENT -.sp -> \fINew in version 0.2.0\fP\&. .UNINDENT .INDENT 0.0 .TP @@ -199,10 +196,9 @@ If \fIvalue\fP is not in between the given conditions. .B Raises .INDENT 7.0 .IP \(bu 2 -\fBValueError\fP \-\- If both \fImin_val\fP and \fImax_val\fP are \fINone\fP, - or if \fImin_val\fP is greater than \fImax_val\fP\&. +\fB(\fP\fBValueError\fP\fB)\fP \-\- If \fImin_val\fP is greater than \fImax_val\fP\&. .IP \(bu 2 -\fBTypeError\fP \-\- If there\(aqs a type mismatch before comparison. +\fB(\fP\fBTypeError\fP\fB)\fP \-\- If there\(aqs a type mismatch during comparison. .UNINDENT .UNINDENT .sp @@ -213,12 +209,86 @@ If \fIvalue\fP is not in between the given conditions. .IP \(bu 2 \fIPossibleValueTypes\fP = \fITypeVar(\(dqPossibleValueTypes\(dq, int, float, str, datetime)\fP .IP \(bu 2 -Either one of \fImin_val\fP or \fImax_val\fP must be provided. +If neither \fImin_val\fP nor \fImax_val\fP is provided, result will always be \fITrue\fP\&. .UNINDENT .UNINDENT .UNINDENT +.UNINDENT +.INDENT 0.0 +.TP +.B validators.between.between(value: PossibleValueTypes, /, *, min_val: PossibleValueTypes | AbsMin | None = None, max_val: PossibleValueTypes | AbsMax | None = None) +Validate that a number is between minimum and/or maximum value. .sp -> \fINew in version 0.2.0\fP\&. +This will work with any comparable type, such as floats, decimals and dates +not just integers. This validator is originally based on [WTForms\-NumberRange\-Validator][1]. +.sp +[1]: \fI\%https://github.com/wtforms/wtforms/blob/master/src/wtforms/validators.py#L166\-L220\fP +.sp +Examples +.sp +.nf +.ft C +>>> from datetime import datetime +>>> between(5, min_val=2) +# Output: True +>>> between(13.2, min_val=13, max_val=14) +# Output: True +>>> between(500, max_val=400) +# Output: ValidationError(func=between, args=...) +>>> between( +\&... datetime(2000, 11, 11), +\&... min_val=datetime(1999, 11, 11) +\&... ) +# Output: True +.ft P +.fi +.INDENT 7.0 +.TP +.B Parameters +.INDENT 7.0 +.IP \(bu 2 +\fBvalue\fP \-\- Value which is to be compared. +.IP \(bu 2 +\fBmin_val\fP \-\- The minimum required value of the number. +If not provided, minimum value will not be checked. +.IP \(bu 2 +\fBmax_val\fP \-\- The maximum value of the number. +If not provided, maximum value will not be checked. +.UNINDENT +.TP +.B Returns +If \fIvalue\fP is in between the given conditions. +(ValidationError): +.INDENT 7.0 +.INDENT 3.5 +If \fIvalue\fP is not in between the given conditions. +.UNINDENT +.UNINDENT + +.TP +.B Return type +(Literal[True]) +.TP +.B Raises +.INDENT 7.0 +.IP \(bu 2 +\fB(\fP\fBValueError\fP\fB)\fP \-\- If \fImin_val\fP is greater than \fImax_val\fP\&. +.IP \(bu 2 +\fB(\fP\fBTypeError\fP\fB)\fP \-\- If there\(aqs a type mismatch during comparison. +.UNINDENT +.UNINDENT +.sp +\fBNOTE:\fP +.INDENT 7.0 +.INDENT 3.5 +.INDENT 0.0 +.IP \(bu 2 +\fIPossibleValueTypes\fP = \fITypeVar(\(dqPossibleValueTypes\(dq, int, float, str, datetime)\fP +.IP \(bu 2 +If neither \fImin_val\fP nor \fImax_val\fP is provided, result will always be \fITrue\fP\&. +.UNINDENT +.UNINDENT +.UNINDENT .UNINDENT .SS btc_address .INDENT 0.0 @@ -294,6 +364,46 @@ If \fIvalue\fP is an invalid bitcoin address. .UNINDENT .UNINDENT +.TP +.B Return type +(Literal[True]) +.UNINDENT +.sp +> \fINew in version 0.18.0\fP\&. +.UNINDENT +.INDENT 0.0 +.TP +.B validators.btc_address.btc_address(value: str, /) +Return whether or not given value is a valid bitcoin address. +.sp +Full validation is implemented for P2PKH and P2SH addresses. +For segwit addresses a regexp is used to provide a reasonable +estimate on whether the address is valid. +.sp +Examples +.sp +.nf +.ft C +>>> btc_address(\(aq3Cwgr2g7vsi1bXDUkpEnVoRLA9w4FZfC69\(aq) +# Output: True +>>> btc_address(\(aq1BvBMsEYstWetqTFn5Au4m4GFg7xJaNVN2\(aq) +# Output: ValidationError(func=btc_address, args=...) +.ft P +.fi +.INDENT 7.0 +.TP +.B Parameters +\fBvalue\fP \-\- Bitcoin address string to validate. +.TP +.B Returns +If \fIvalue\fP is a valid bitcoin address. +(ValidationError): +.INDENT 7.0 +.INDENT 3.5 +If \fIvalue\fP is an invalid bitcoin address. +.UNINDENT +.UNINDENT + .TP .B Return type (Literal[True]) @@ -304,6 +414,42 @@ If \fIvalue\fP is an invalid bitcoin address. .SS card .INDENT 0.0 .TP +.B validators.card.visa(value: str, /) +Return whether or not given value is a valid Visa card number. +.sp +Examples +.sp +.nf +.ft C +>>> visa(\(aq4242424242424242\(aq) +# Output: True +>>> visa(\(aq2223003122003222\(aq) +# Output: ValidationError(func=visa, args={\(aqvalue\(aq: \(aq2223003122003222\(aq}) +.ft P +.fi +.INDENT 7.0 +.TP +.B Parameters +\fBvalue\fP \-\- Visa card number string to validate +.TP +.B Returns +If \fIvalue\fP is a valid Visa card number. +(ValidationError): +.INDENT 7.0 +.INDENT 3.5 +If \fIvalue\fP is an invalid Visa card number. +.UNINDENT +.UNINDENT + +.TP +.B Return type +(Literal[True]) +.UNINDENT +.sp +> \fINew in version 0.15.0\fP\&. +.UNINDENT +.INDENT 0.0 +.TP .B validators.card.amex(value: str, /) Return whether or not given value is a valid American Express card number. .sp @@ -982,6 +1128,56 @@ If \fIvalue\fP is an invalid country code. .UNINDENT .UNINDENT +.TP +.B Return type +(Literal[True]) +.UNINDENT +.UNINDENT +.INDENT 0.0 +.TP +.B validators.country_code.country_code(value: str, /, *, iso_format: str = \(aqauto\(aq) +Validates given country code. +.sp +This performs a case\-sensitive [ISO 3166][1] country code validation. +.sp +[1]: \fI\%https://www.iso.org/iso\-3166\-country\-codes.html\fP +.sp +Examples +.sp +.nf +.ft C +>>> country_code(\(aqGB\(aq, iso_format=\(aqalpha3\(aq) +# Output: False +>>> country_code(\(aqUSA\(aq) +# Output: True +>>> country_code(\(aq840\(aq, iso_format=\(aqnumeric\(aq) +# Output: True +>>> country_code(\(aqiN\(aq, iso_format=\(aqalpha2\(aq) +# Output: False +>>> country_code(\(aqZWE\(aq, iso_format=\(aqalpha3\(aq) +# Output: True +.ft P +.fi +.INDENT 7.0 +.TP +.B Parameters +.INDENT 7.0 +.IP \(bu 2 +\fBvalue\fP \-\- Country code string to validate. +.IP \(bu 2 +\fBiso_format\fP \-\- ISO format to be used. Available options are: +\fIauto\fP, \fIalpha2\fP, \fIalpha3\fP and \fInumeric\fP\&. +.UNINDENT +.TP +.B Returns +If \fIvalue\fP is a valid country code. +(ValidationError): +.INDENT 7.0 +.INDENT 3.5 +If \fIvalue\fP is an invalid country code. +.UNINDENT +.UNINDENT + .TP .B Return type (Literal[True]) @@ -1118,28 +1314,22 @@ Added support for internationalized domain name (IDN) validation. .sp > \fINew in version 0.9.0\fP\&. .UNINDENT -.SS email .INDENT 0.0 .TP -.B validators.email.email(value: str, /, *, ipv6_address: bool = False, ipv4_address: bool = False, simple_host: bool = False, rfc_1034: bool = False, rfc_2782: bool = False) -Validate an email address. -.sp -This was inspired from [Django\(aqs email validator][1]. -Also ref: [RFC 1034][2], [RFC 5321][3] and [RFC 5322][4]. -.sp -[1]: \fI\%https://github.com/django/django/blob/main/django/core/validators.py#L174\fP -[2]: \fI\%https://www.rfc\-editor.org/rfc/rfc1034\fP -[3]: \fI\%https://www.rfc\-editor.org/rfc/rfc5321\fP -[4]: \fI\%https://www.rfc\-editor.org/rfc/rfc5322\fP +.B validators.domain.domain(value: str, /, *, rfc_1034: bool = False, rfc_2782: bool = False) +Return whether or not given value is a valid domain. .sp Examples .sp .nf .ft C ->>> email(\(aqsomeone@example.com\(aq) +>>> domain(\(aqexample.com\(aq) +# Output: True +>>> domain(\(aqexample.com/\(aq) +# Output: ValidationError(func=domain, ...) +>>> # Supports IDN domains as well:: +>>> domain(\(aqxn\-\-\-\-gtbspbbmkef.xn\-\-p1ai\(aq) # Output: True ->>> email(\(aqbogus@@\(aq) -# Output: ValidationError(email=email, args={\(aqvalue\(aq: \(aqbogus@@\(aq}) .ft P .fi .INDENT 7.0 @@ -1147,13 +1337,7 @@ Examples .B Parameters .INDENT 7.0 .IP \(bu 2 -\fBvalue\fP \-\- eMail string to validate. -.IP \(bu 2 -\fBipv6_address\fP \-\- When the domain part is an IPv6 address. -.IP \(bu 2 -\fBipv4_address\fP \-\- When the domain part is an IPv4 address. -.IP \(bu 2 -\fBsimple_host\fP \-\- When the domain part is a simple hostname. +\fBvalue\fP \-\- Domain string to validate. .IP \(bu 2 \fBrfc_1034\fP \-\- Allow trailing dot in domain name. Ref: [RFC 1034](\fI\%https://www.rfc\-editor.org/rfc/rfc1034\fP). @@ -1163,11 +1347,11 @@ Ref: [RFC 2782](\fI\%https://www.rfc\-editor.org/rfc/rfc2782\fP). .UNINDENT .TP .B Returns -If \fIvalue\fP is a valid eMail. +If \fIvalue\fP is a valid domain name. (ValidationError): .INDENT 7.0 .INDENT 3.5 -If \fIvalue\fP is an invalid eMail. +If \fIvalue\fP is an invalid domain name. .UNINDENT .UNINDENT @@ -1176,8 +1360,26 @@ If \fIvalue\fP is an invalid eMail. (Literal[True]) .UNINDENT .sp -> \fINew in version 0.1.0\fP\&. +\fBNOTE:\fP +.INDENT 7.0 +.INDENT 3.5 +.INDENT 0.0 +.IP \(bu 2 +.INDENT 2.0 +.TP +.B \fIIn version 0.10.0\fP: +.INDENT 7.0 +.IP \(bu 2 +Added support for internationalized domain name (IDN) validation. +.UNINDENT .UNINDENT +.UNINDENT +.UNINDENT +.UNINDENT +.sp +> \fINew in version 0.9.0\fP\&. +.UNINDENT +.SS email .INDENT 0.0 .TP .B validators.email.email(value: str, /, *, ipv6_address: bool = False, ipv4_address: bool = False, simple_host: bool = False, rfc_1034: bool = False, rfc_2782: bool = False) @@ -1237,7 +1439,165 @@ If \fIvalue\fP is an invalid eMail. .sp > \fINew in version 0.1.0\fP\&. .UNINDENT -.SS hashes +.INDENT 0.0 +.TP +.B validators.email.email(value: str, /, *, ipv6_address: bool = False, ipv4_address: bool = False, simple_host: bool = False, rfc_1034: bool = False, rfc_2782: bool = False) +Validate an email address. +.sp +This was inspired from [Django\(aqs email validator][1]. +Also ref: [RFC 1034][2], [RFC 5321][3] and [RFC 5322][4]. +.sp +[1]: \fI\%https://github.com/django/django/blob/main/django/core/validators.py#L174\fP +[2]: \fI\%https://www.rfc\-editor.org/rfc/rfc1034\fP +[3]: \fI\%https://www.rfc\-editor.org/rfc/rfc5321\fP +[4]: \fI\%https://www.rfc\-editor.org/rfc/rfc5322\fP +.sp +Examples +.sp +.nf +.ft C +>>> email(\(aqsomeone@example.com\(aq) +# Output: True +>>> email(\(aqbogus@@\(aq) +# Output: ValidationError(email=email, args={\(aqvalue\(aq: \(aqbogus@@\(aq}) +.ft P +.fi +.INDENT 7.0 +.TP +.B Parameters +.INDENT 7.0 +.IP \(bu 2 +\fBvalue\fP \-\- eMail string to validate. +.IP \(bu 2 +\fBipv6_address\fP \-\- When the domain part is an IPv6 address. +.IP \(bu 2 +\fBipv4_address\fP \-\- When the domain part is an IPv4 address. +.IP \(bu 2 +\fBsimple_host\fP \-\- When the domain part is a simple hostname. +.IP \(bu 2 +\fBrfc_1034\fP \-\- Allow trailing dot in domain name. +Ref: [RFC 1034](\fI\%https://www.rfc\-editor.org/rfc/rfc1034\fP). +.IP \(bu 2 +\fBrfc_2782\fP \-\- Domain name is of type service record. +Ref: [RFC 2782](\fI\%https://www.rfc\-editor.org/rfc/rfc2782\fP). +.UNINDENT +.TP +.B Returns +If \fIvalue\fP is a valid eMail. +(ValidationError): +.INDENT 7.0 +.INDENT 3.5 +If \fIvalue\fP is an invalid eMail. +.UNINDENT +.UNINDENT + +.TP +.B Return type +(Literal[True]) +.UNINDENT +.sp +> \fINew in version 0.1.0\fP\&. +.UNINDENT +.INDENT 0.0 +.TP +.B validators.email.email(value: str, /, *, ipv6_address: bool = False, ipv4_address: bool = False, simple_host: bool = False, rfc_1034: bool = False, rfc_2782: bool = False) +Validate an email address. +.sp +This was inspired from [Django\(aqs email validator][1]. +Also ref: [RFC 1034][2], [RFC 5321][3] and [RFC 5322][4]. +.sp +[1]: \fI\%https://github.com/django/django/blob/main/django/core/validators.py#L174\fP +[2]: \fI\%https://www.rfc\-editor.org/rfc/rfc1034\fP +[3]: \fI\%https://www.rfc\-editor.org/rfc/rfc5321\fP +[4]: \fI\%https://www.rfc\-editor.org/rfc/rfc5322\fP +.sp +Examples +.sp +.nf +.ft C +>>> email(\(aqsomeone@example.com\(aq) +# Output: True +>>> email(\(aqbogus@@\(aq) +# Output: ValidationError(email=email, args={\(aqvalue\(aq: \(aqbogus@@\(aq}) +.ft P +.fi +.INDENT 7.0 +.TP +.B Parameters +.INDENT 7.0 +.IP \(bu 2 +\fBvalue\fP \-\- eMail string to validate. +.IP \(bu 2 +\fBipv6_address\fP \-\- When the domain part is an IPv6 address. +.IP \(bu 2 +\fBipv4_address\fP \-\- When the domain part is an IPv4 address. +.IP \(bu 2 +\fBsimple_host\fP \-\- When the domain part is a simple hostname. +.IP \(bu 2 +\fBrfc_1034\fP \-\- Allow trailing dot in domain name. +Ref: [RFC 1034](\fI\%https://www.rfc\-editor.org/rfc/rfc1034\fP). +.IP \(bu 2 +\fBrfc_2782\fP \-\- Domain name is of type service record. +Ref: [RFC 2782](\fI\%https://www.rfc\-editor.org/rfc/rfc2782\fP). +.UNINDENT +.TP +.B Returns +If \fIvalue\fP is a valid eMail. +(ValidationError): +.INDENT 7.0 +.INDENT 3.5 +If \fIvalue\fP is an invalid eMail. +.UNINDENT +.UNINDENT + +.TP +.B Return type +(Literal[True]) +.UNINDENT +.sp +> \fINew in version 0.1.0\fP\&. +.UNINDENT +.SS hashes +.INDENT 0.0 +.TP +.B validators.hashes.sha512(value: str, /) +Return whether or not given value is a valid SHA512 hash. +.sp +Examples +.sp +.nf +.ft C +>>> sha512( +\&... \(aqcf83e1357eefb8bdf1542850d66d8007d620e4050b5715dc83f4a921d36ce\(aq +\&... \(aq9ce47d0d13c5d85f2b0ff8318d2877eec2f63b931bd47417a81a538327af9\(aq +\&... \(aq27da3e\(aq +\&... ) +# Output: True +>>> sha512(\(aq900zz11\(aq) +# Output: ValidationError(func=sha512, args={\(aqvalue\(aq: \(aq900zz11\(aq}) +.ft P +.fi +.INDENT 7.0 +.TP +.B Parameters +\fBvalue\fP \-\- SHA512 string to validate. +.TP +.B Returns +If \fIvalue\fP is a valid SHA512 hash. +(ValidationError): +.INDENT 7.0 +.INDENT 3.5 +If \fIvalue\fP is an invalid SHA512 hash. +.UNINDENT +.UNINDENT + +.TP +.B Return type +(Literal[True]) +.UNINDENT +.sp +> \fINew in version 0.12.1\fP +.UNINDENT .INDENT 0.0 .TP .B validators.hashes.md5(value: str, /) @@ -1751,46 +2111,65 @@ If \fIvalue\fP is an invalid hostname. .sp > \fINew in version 0.21.0\fP\&. .UNINDENT -.SS i18n .INDENT 0.0 .TP -.B validators.i18n.es_cif(value: str, /) -Validate a Spanish CIF. -.sp -Each company in Spain prior to 2008 had a distinct CIF and has been -discontinued. For more information see [wikipedia.org/cif][1]. -.sp -The new replacement is to use NIF for absolutely everything. The issue is -that there are \(dqtypes\(dq of NIFs now: company, person [citizen or resident] -all distinguished by the first character of the DOI. For this reason we -will continue to call CIFs NIFs, that are used for companies. -.sp -This validator is based on [generadordni.es][2]. -.sp -[1]: \fI\%https://es.wikipedia.org/wiki/C%C3%B3digo_de_identificaci%C3%B3n_fiscal\fP -[2]: \fI\%https://generadordni.es/\fP +.B validators.hostname.hostname(value: str, /, *, skip_ipv6_addr: bool = False, skip_ipv4_addr: bool = False, may_have_port: bool = True, maybe_simple: bool = True, rfc_1034: bool = False, rfc_2782: bool = False) +Return whether or not given value is a valid hostname. .sp Examples .sp .nf .ft C ->>> es_cif(\(aqB25162520\(aq) +>>> hostname(\(dqubuntu\-pc:443\(dq) # Output: True ->>> es_cif(\(aqB25162529\(aq) -# Output: ValidationError(func=es_cif, args=...) +>>> hostname(\(dqthis\-pc\(dq) +# Output: True +>>> hostname(\(dqxn\-\-\-\-gtbspbbmkef.xn\-\-p1ai:65535\(dq) +# Output: True +>>> hostname(\(dq_example.com\(dq) +# Output: True +>>> hostname(\(dq123.5.77.88:31000\(dq) +# Output: True +>>> hostname(\(dq12.12.12.12\(dq) +# Output: True +>>> hostname(\(dq[::1]:22\(dq) +# Output: True +>>> hostname(\(dqdead:beef:0:0:0:0000:42:1\(dq) +# Output: True +>>> hostname(\(dq[0:0:0:0:0:ffff:1.2.3.4]:\-65538\(dq) +# Output: ValidationError(func=hostname, ...) +>>> hostname(\(dq[0:&:b:c:@:e:f::]:9999\(dq) +# Output: ValidationError(func=hostname, ...) .ft P .fi .INDENT 7.0 .TP .B Parameters -\fBvalue\fP \-\- DOI string which is to be validated. +.INDENT 7.0 +.IP \(bu 2 +\fBvalue\fP \-\- Hostname string to validate. +.IP \(bu 2 +\fBskip_ipv6_addr\fP \-\- When hostname string cannot be an IPv6 address. +.IP \(bu 2 +\fBskip_ipv4_addr\fP \-\- When hostname string cannot be an IPv4 address. +.IP \(bu 2 +\fBmay_have_port\fP \-\- Hostname string may contain port number. +.IP \(bu 2 +\fBmaybe_simple\fP \-\- Hostname string maybe only hyphens and alpha\-numerals. +.IP \(bu 2 +\fBrfc_1034\fP \-\- Allow trailing dot in domain/host name. +Ref: [RFC 1034](\fI\%https://www.rfc\-editor.org/rfc/rfc1034\fP). +.IP \(bu 2 +\fBrfc_2782\fP \-\- Domain/Host name is of type service record. +Ref: [RFC 2782](\fI\%https://www.rfc\-editor.org/rfc/rfc2782\fP). +.UNINDENT .TP .B Returns -If \fIvalue\fP is a valid DOI string. +If \fIvalue\fP is a valid hostname. (ValidationError): .INDENT 7.0 .INDENT 3.5 -If \fIvalue\fP is an invalid DOI string. +If \fIvalue\fP is an invalid hostname. .UNINDENT .UNINDENT @@ -1799,41 +2178,44 @@ If \fIvalue\fP is an invalid DOI string. (Literal[True]) .UNINDENT .sp -> \fINew in version 0.13.0\fP\&. +> \fINew in version 0.21.0\fP\&. .UNINDENT +.SS i18n .INDENT 0.0 .TP -.B validators.i18n.es_doi(value: str, /) -Validate a Spanish DOI. +.B validators.i18n.fr_ssn(value: str) +Validate a french Social Security Number. .sp -A DOI in spain is all NIF / CIF / NIE / DNI \-\- a digital ID. -For more information see [wikipedia.org/doi][1]. This validator -is based on [generadordni.es][2]. +Each french citizen has a distinct Social Security Number. +For more information see [French Social Security Number][1] (sadly unavailable in english). .sp -[1]: \fI\%https://es.wikipedia.org/wiki/Identificador_de_objeto_digital\fP -[2]: \fI\%https://generadordni.es/\fP +[1]: \fI\%https://fr.wikipedia.org/wiki/Num%C3%A9ro_de_s%C3%A9curit%C3%A9_sociale_en_France\fP .sp Examples .sp .nf .ft C ->>> es_doi(\(aqX0095892M\(aq) +>>> fr_ssn(\(aq1 84 12 76 451 089 46\(aq) # Output: True ->>> es_doi(\(aqX0095892X\(aq) -# Output: ValidationError(func=es_doi, args=...) +>>> fr_ssn(\(aq1 84 12 76 451 089\(aq) # control key is optional +# Output: True +>>> fr_ssn(\(aq3 84 12 76 451 089 46\(aq) # wrong gender number +# Output: ValidationError(func=fr_ssn, args=...) +>>> fr_ssn(\(aq1 84 12 76 451 089 47\(aq) # wrong control key +# Output: ValidationError(func=fr_ssn, args=...) .ft P .fi .INDENT 7.0 .TP .B Parameters -\fBvalue\fP \-\- DOI string which is to be validated. +\fBvalue\fP \-\- French Social Security Number string to validate. .TP .B Returns -If \fIvalue\fP is a valid DOI string. +If \fIvalue\fP is a valid french Social Security Number. (ValidationError): .INDENT 7.0 .INDENT 3.5 -If \fIvalue\fP is an invalid DOI string. +If \fIvalue\fP is an invalid french Social Security Number. .UNINDENT .UNINDENT @@ -1842,11 +2224,103 @@ If \fIvalue\fP is an invalid DOI string. (Literal[True]) .UNINDENT .sp -> \fINew in version 0.13.0\fP\&. +> \fINew in version 0.23.0\fP\&. .UNINDENT .INDENT 0.0 .TP -.B validators.i18n.es_nie(value: str, /) +.B validators.i18n.es_cif(value: str, /) +Validate a Spanish CIF. +.sp +Each company in Spain prior to 2008 had a distinct CIF and has been +discontinued. For more information see [wikipedia.org/cif][1]. +.sp +The new replacement is to use NIF for absolutely everything. The issue is +that there are \(dqtypes\(dq of NIFs now: company, person [citizen or resident] +all distinguished by the first character of the DOI. For this reason we +will continue to call CIFs NIFs, that are used for companies. +.sp +This validator is based on [generadordni.es][2]. +.sp +[1]: \fI\%https://es.wikipedia.org/wiki/C%C3%B3digo_de_identificaci%C3%B3n_fiscal\fP +[2]: \fI\%https://generadordni.es/\fP +.sp +Examples +.sp +.nf +.ft C +>>> es_cif(\(aqB25162520\(aq) +# Output: True +>>> es_cif(\(aqB25162529\(aq) +# Output: ValidationError(func=es_cif, args=...) +.ft P +.fi +.INDENT 7.0 +.TP +.B Parameters +\fBvalue\fP \-\- DOI string which is to be validated. +.TP +.B Returns +If \fIvalue\fP is a valid DOI string. +(ValidationError): +.INDENT 7.0 +.INDENT 3.5 +If \fIvalue\fP is an invalid DOI string. +.UNINDENT +.UNINDENT + +.TP +.B Return type +(Literal[True]) +.UNINDENT +.sp +> \fINew in version 0.13.0\fP\&. +.UNINDENT +.INDENT 0.0 +.TP +.B validators.i18n.es_doi(value: str, /) +Validate a Spanish DOI. +.sp +A DOI in spain is all NIF / CIF / NIE / DNI \-\- a digital ID. +For more information see [wikipedia.org/doi][1]. This validator +is based on [generadordni.es][2]. +.sp +[1]: \fI\%https://es.wikipedia.org/wiki/Identificador_de_objeto_digital\fP +[2]: \fI\%https://generadordni.es/\fP +.sp +Examples +.sp +.nf +.ft C +>>> es_doi(\(aqX0095892M\(aq) +# Output: True +>>> es_doi(\(aqX0095892X\(aq) +# Output: ValidationError(func=es_doi, args=...) +.ft P +.fi +.INDENT 7.0 +.TP +.B Parameters +\fBvalue\fP \-\- DOI string which is to be validated. +.TP +.B Returns +If \fIvalue\fP is a valid DOI string. +(ValidationError): +.INDENT 7.0 +.INDENT 3.5 +If \fIvalue\fP is an invalid DOI string. +.UNINDENT +.UNINDENT + +.TP +.B Return type +(Literal[True]) +.UNINDENT +.sp +> \fINew in version 0.13.0\fP\&. +.UNINDENT +.INDENT 0.0 +.TP +.B validators.i18n.es_nie(value: str, /) Validate a Spanish NIE. .sp The NIE is a tax identification number in Spain, known in Spanish @@ -2570,6 +3044,42 @@ If \fIvalue\fP is an invalid IBAN code. .UNINDENT .UNINDENT +.TP +.B Return type +(Literal[True]) +.UNINDENT +.sp +> \fINew in version 0.8.0\fP +.UNINDENT +.INDENT 0.0 +.TP +.B validators.iban.iban(value: str, /) +Return whether or not given value is a valid IBAN code. +.sp +Examples +.sp +.nf +.ft C +>>> iban(\(aqDE29100500001061045672\(aq) +# Output: True +>>> iban(\(aq123456\(aq) +# Output: ValidationError(func=iban, ...) +.ft P +.fi +.INDENT 7.0 +.TP +.B Parameters +\fBvalue\fP \-\- IBAN string to validate. +.TP +.B Returns +If \fIvalue\fP is a valid IBAN code. +(ValidationError): +.INDENT 7.0 +.INDENT 3.5 +If \fIvalue\fP is an invalid IBAN code. +.UNINDENT +.UNINDENT + .TP .B Return type (Literal[True]) @@ -2580,6 +3090,77 @@ If \fIvalue\fP is an invalid IBAN code. .SS ip_address .INDENT 0.0 .TP +.B validators.ip_address.ipv6(value: str, /, *, cidr: bool = True, strict: bool = False, host_bit: bool = True) +Returns if a given value is a valid IPv6 address. +.sp +Including IPv4\-mapped IPv6 addresses. The initial version of ipv6 validator +was inspired from [WTForms IPAddress validator][1]. +.sp +[1]: \fI\%https://github.com/wtforms/wtforms/blob/master/src/wtforms/validators.py\fP +.sp +Examples +.sp +.nf +.ft C +>>> ipv6(\(aq::ffff:192.0.2.128\(aq) +# Output: True +>>> ipv6(\(aq::1/128\(aq) +# Output: True +>>> ipv6(\(aqabc.0.0.1\(aq) +# Output: ValidationError(func=ipv6, args={\(aqvalue\(aq: \(aqabc.0.0.1\(aq}) +.ft P +.fi +.INDENT 7.0 +.TP +.B Parameters +.INDENT 7.0 +.IP \(bu 2 +\fBvalue\fP \-\- IP address string to validate. +.IP \(bu 2 +\fBcidr\fP \-\- IP address string may contain CIDR annotation +.IP \(bu 2 +\fBstrict\fP \-\- IP address string is strictly in CIDR notation +.IP \(bu 2 +\fBhost_bit\fP \-\- If \fIFalse\fP and host bits (along with network bits) _are_ set in the supplied +address, this function raises a validation error. ref [IPv6Network][2]. +[2]: \fI\%https://docs.python.org/3/library/ipaddress.html#ipaddress.IPv6Network\fP +.UNINDENT +.TP +.B Returns +If \fIvalue\fP is a valid IPv6 address. +(ValidationError): +.INDENT 7.0 +.INDENT 3.5 +If \fIvalue\fP is an invalid IPv6 address. +.UNINDENT +.UNINDENT + +.TP +.B Return type +(Literal[True]) +.UNINDENT +.sp +\fBNOTE:\fP +.INDENT 7.0 +.INDENT 3.5 +.INDENT 0.0 +.IP \(bu 2 +.INDENT 2.0 +.TP +.B \fIIn version 0.14.0\fP: +.INDENT 7.0 +.IP \(bu 2 +Add supports for CIDR notation +.UNINDENT +.UNINDENT +.UNINDENT +.UNINDENT +.UNINDENT +.sp +> \fINew in version 0.2.0\fP +.UNINDENT +.INDENT 0.0 +.TP .B validators.ip_address.ipv4(value: str, /, *, cidr: bool = True, strict: bool = False, host_bit: bool = True) Returns whether a given value is a valid IPv4 address. .sp @@ -2867,7 +3448,7 @@ Add supports for CIDR notation .SS length .INDENT 0.0 .TP -.B validators.length.length(value: str, /, *, min_val: int = 0, max_val: int = 0) +.B validators.length.length(value: str, /, *, min_val: int | None = None, max_val: int | None = None) Return whether or not the length of given string is within a specified range. .sp Examples @@ -2908,13 +3489,14 @@ If \fIlen(value)\fP is not in between the given conditions. .TP .B Return type (Literal[True]) +.TP +.B Raises +\fB(\fP\fBValueError\fP\fB)\fP \-\- If either \fImin_val\fP or \fImax_val\fP is negative. .UNINDENT -.sp -> \fINew in version 0.2.0\fP\&. .UNINDENT .INDENT 0.0 .TP -.B validators.length.length(value: str, /, *, min_val: int = 0, max_val: int = 0) +.B validators.length.length(value: str, /, *, min_val: int | None = None, max_val: int | None = None) Return whether or not the length of given string is within a specified range. .sp Examples @@ -2955,9 +3537,58 @@ If \fIlen(value)\fP is not in between the given conditions. .TP .B Return type (Literal[True]) +.TP +.B Raises +\fB(\fP\fBValueError\fP\fB)\fP \-\- If either \fImin_val\fP or \fImax_val\fP is negative. .UNINDENT +.UNINDENT +.INDENT 0.0 +.TP +.B validators.length.length(value: str, /, *, min_val: int | None = None, max_val: int | None = None) +Return whether or not the length of given string is within a specified range. .sp -> \fINew in version 0.2.0\fP\&. +Examples +.sp +.nf +.ft C +>>> length(\(aqsomething\(aq, min_val=2) +# Output: True +>>> length(\(aqsomething\(aq, min_val=9, max_val=9) +# Output: True +>>> length(\(aqsomething\(aq, max_val=5) +# Output: ValidationError(func=length, ...) +.ft P +.fi +.INDENT 7.0 +.TP +.B Parameters +.INDENT 7.0 +.IP \(bu 2 +\fBvalue\fP \-\- The string to validate. +.IP \(bu 2 +\fBmin_val\fP \-\- The minimum required length of the string. If not provided, +minimum length will not be checked. +.IP \(bu 2 +\fBmax_val\fP \-\- The maximum length of the string. If not provided, +maximum length will not be checked. +.UNINDENT +.TP +.B Returns +If \fIlen(value)\fP is in between the given conditions. +(ValidationError): +.INDENT 7.0 +.INDENT 3.5 +If \fIlen(value)\fP is not in between the given conditions. +.UNINDENT +.UNINDENT + +.TP +.B Return type +(Literal[True]) +.TP +.B Raises +\fB(\fP\fBValueError\fP\fB)\fP \-\- If either \fImin_val\fP or \fImax_val\fP is negative. +.UNINDENT .UNINDENT .SS mac_address .INDENT 0.0 @@ -3040,12 +3671,91 @@ If \fIvalue\fP is an invalid MAC address. .sp > \fINew in version 0.2.0\fP\&. .UNINDENT -.SS slug .INDENT 0.0 .TP -.B validators.slug.slug(value: str, /) -Validate whether or not given value is valid slug. -.sp +.B validators.mac_address.mac_address(value: str, /) +Return whether or not given value is a valid MAC address. +.sp +This validator is based on [WTForms MacAddress validator][1]. +.sp +[1]: \fI\%https://github.com/wtforms/wtforms/blob/master/src/wtforms/validators.py#L482\fP +.sp +Examples +.sp +.nf +.ft C +>>> mac_address(\(aq01:23:45:67:ab:CD\(aq) +# Output: True +>>> mac_address(\(aq00:00:00:00:00\(aq) +# Output: ValidationError(func=mac_address, args={\(aqvalue\(aq: \(aq00:00:00:00:00\(aq}) +.ft P +.fi +.INDENT 7.0 +.TP +.B Parameters +\fBvalue\fP \-\- MAC address string to validate. +.TP +.B Returns +If \fIvalue\fP is a valid MAC address. +(ValidationError): +.INDENT 7.0 +.INDENT 3.5 +If \fIvalue\fP is an invalid MAC address. +.UNINDENT +.UNINDENT + +.TP +.B Return type +(Literal[True]) +.UNINDENT +.sp +> \fINew in version 0.2.0\fP\&. +.UNINDENT +.SS slug +.INDENT 0.0 +.TP +.B validators.slug.slug(value: str, /) +Validate whether or not given value is valid slug. +.sp +Valid slug can contain only lowercase alphanumeric characters and hyphens. +It starts and ends with these lowercase alphanumeric characters. +.sp +Examples +.sp +.nf +.ft C +>>> slug(\(aqmy\-slug\-2134\(aq) +# Output: True +>>> slug(\(aqmy.slug\(aq) +# Output: ValidationError(func=slug, args={\(aqvalue\(aq: \(aqmy.slug\(aq}) +.ft P +.fi +.INDENT 7.0 +.TP +.B Parameters +\fBvalue\fP \-\- Slug string to validate. +.TP +.B Returns +If \fIvalue\fP is a valid slug. +(ValidationError): +.INDENT 7.0 +.INDENT 3.5 +If \fIvalue\fP is an invalid slug. +.UNINDENT +.UNINDENT + +.TP +.B Return type +(Literal[True]) +.UNINDENT +.sp +> \fINew in version 0.6.0\fP\&. +.UNINDENT +.INDENT 0.0 +.TP +.B validators.slug.slug(value: str, /) +Validate whether or not given value is valid slug. +.sp Valid slug can contain only lowercase alphanumeric characters and hyphens. It starts and ends with these lowercase alphanumeric characters. .sp @@ -3329,6 +4039,137 @@ If \fIvalue\fP is an invalid slug. .UNINDENT .UNINDENT +.TP +.B Return type +(Literal[True]) +.UNINDENT +.sp +\fBNOTE:\fP +.INDENT 7.0 +.INDENT 3.5 +.INDENT 0.0 +.IP \(bu 2 +.INDENT 2.0 +.TP +.B \fIIn version 0.11.3\fP: +.INDENT 7.0 +.IP \(bu 2 +Added support for URLs containing localhost. +.UNINDENT +.UNINDENT +.IP \(bu 2 +.INDENT 2.0 +.TP +.B \fIIn version 0.11.0\fP: +.INDENT 7.0 +.IP \(bu 2 +Made the regular expression case insensitive. +.UNINDENT +.UNINDENT +.IP \(bu 2 +.INDENT 2.0 +.TP +.B \fIIn version 0.10.3\fP: +.INDENT 7.0 +.IP \(bu 2 +Added a \fIpublic\fP parameter. +.UNINDENT +.UNINDENT +.IP \(bu 2 +.INDENT 2.0 +.TP +.B \fIIn version 0.10.2\fP: +.INDENT 7.0 +.IP \(bu 2 +Added support for various exotic URLs. +.IP \(bu 2 +Fixed various false positives. +.UNINDENT +.UNINDENT +.UNINDENT +.UNINDENT +.UNINDENT +.sp +> \fINew in version 0.2.0\fP\&. +.UNINDENT +.INDENT 0.0 +.TP +.B validators.url.url(value: str, /, *, skip_ipv6_addr: bool = False, skip_ipv4_addr: bool = False, may_have_port: bool = True, simple_host: bool = False, strict_query: bool = True, rfc_1034: bool = False, rfc_2782: bool = False) +Return whether or not given value is a valid URL. +.sp +This validator was inspired from [URL validator of dperini][1]. +The following diagram is from [urlly][2]. +.INDENT 7.0 +.INDENT 3.5 +.INDENT 0.0 +.INDENT 3.5 +foo://admin:hunter1@example.com:8042/over/there?name=ferret#nose +_/ ___/ _____/ _________/ __/_________/ _________/ __/ +.INDENT 0.0 +.INDENT 3.5 +.nf +| | | | | | | +.fi +.sp +.UNINDENT +.UNINDENT +.UNINDENT +.UNINDENT +.sp +scheme username password hostname port path query fragment +.UNINDENT +.UNINDENT +.sp +[1]: \fI\%https://gist.github.com/dperini/729294\fP +[2]: \fI\%https://github.com/treeform/urlly\fP +.sp +Examples +.sp +.nf +.ft C +>>> url(\(aqhttp://duck.com\(aq) +# Output: True +>>> url(\(aqftp://foobar.dk\(aq) +# Output: True +>>> url(\(aqhttp://10.0.0.1\(aq) +# Output: True +>>> url(\(aqhttp://example.com/\(dq>user@example.com\(aq) +# Output: ValidationError(func=url, ...) +.ft P +.fi +.INDENT 7.0 +.TP +.B Parameters +.INDENT 7.0 +.IP \(bu 2 +\fBvalue\fP \-\- URL string to validate. +.IP \(bu 2 +\fBskip_ipv6_addr\fP \-\- When URL string cannot contain an IPv6 address. +.IP \(bu 2 +\fBskip_ipv4_addr\fP \-\- When URL string cannot contain an IPv4 address. +.IP \(bu 2 +\fBmay_have_port\fP \-\- URL string may contain port number. +.IP \(bu 2 +\fBsimple_host\fP \-\- URL string maybe only hyphens and alpha\-numerals. +.IP \(bu 2 +\fBstrict_query\fP \-\- Fail validation on query string parsing error. +.IP \(bu 2 +\fBrfc_1034\fP \-\- Allow trailing dot in domain/host name. +Ref: [RFC 1034](\fI\%https://www.rfc\-editor.org/rfc/rfc1034\fP). +.IP \(bu 2 +\fBrfc_2782\fP \-\- Domain/Host name is of type service record. +Ref: [RFC 2782](\fI\%https://www.rfc\-editor.org/rfc/rfc2782\fP). +.UNINDENT +.TP +.B Returns +If \fIvalue\fP is a valid slug. +(ValidationError): +.INDENT 7.0 +.INDENT 3.5 +If \fIvalue\fP is an invalid slug. +.UNINDENT +.UNINDENT + .TP .B Return type (Literal[True]) @@ -3385,6 +4226,42 @@ Fixed various false positives. .SS utils .INDENT 0.0 .TP +.B validators.utils.validator(func: Callable[[\&...], Any]) +A decorator that makes given function validator. +.sp +Whenever the given \fIfunc\fP returns \fIFalse\fP this +decorator returns \fIValidationError\fP object. +.sp +Examples +.sp +.nf +.ft C +>>> @validator +\&... def even(value): +\&... return not (value % 2) +>>> even(4) +# Output: True +>>> even(5) +# Output: ValidationError(func=even, args={\(aqvalue\(aq: 5}) +.ft P +.fi +.INDENT 7.0 +.TP +.B Parameters +\fBfunc\fP \-\- Function which is to be decorated. +.TP +.B Returns +A decorator which returns either \fIValidationError\fP +or \fILiteral[True]\fP\&. +.TP +.B Return type +(Callable[\&..., ValidationError | Literal[True]]) +.UNINDENT +.sp +> \fINew in version 2013.10.21\fP\&. +.UNINDENT +.INDENT 0.0 +.TP .B validators.utils.ValidationError(function: Callable[[\&...], Any], arg_dict: Dict[str, Any], message: str = \(aq\(aq) Exception class when validation failure occurs. .UNINDENT @@ -3539,6 +4416,46 @@ If \fIvalue\fP is an invalid UUID. .UNINDENT .UNINDENT +.TP +.B Return type +(Literal[True]) +.UNINDENT +.sp +> \fINew in version 0.2.0\fP\&. +.UNINDENT +.INDENT 0.0 +.TP +.B validators.uuid.uuid(value: str | UUID, /) +Return whether or not given value is a valid UUID\-v4 string. +.sp +This validator is based on [WTForms UUID validator][1]. +.sp +[1]: \fI\%https://github.com/wtforms/wtforms/blob/master/src/wtforms/validators.py#L539\fP +.sp +Examples +.sp +.nf +.ft C +>>> uuid(\(aq2bc1c94f\-0deb\-43e9\-92a1\-4775189ec9f8\(aq) +# Output: True +>>> uuid(\(aq2bc1c94f 0deb\-43e9\-92a1\-4775189ec9f8\(aq) +# Output: ValidationError(func=uuid, ...) +.ft P +.fi +.INDENT 7.0 +.TP +.B Parameters +\fBvalue\fP \-\- UUID string or object to validate. +.TP +.B Returns +If \fIvalue\fP is a valid UUID. +(ValidationError): +.INDENT 7.0 +.INDENT 3.5 +If \fIvalue\fP is an invalid UUID. +.UNINDENT +.UNINDENT + .TP .B Return type (Literal[True]) diff --git a/0.23/references/between.rst b/0.23/references/between.rst index 06771af4..db8ed412 100644 --- a/0.23/references/between.rst +++ b/0.23/references/between.rst @@ -5,3 +5,5 @@ between .. autofunction:: between .. module:: validators.between .. autofunction:: between +.. module:: validators.between +.. autofunction:: between diff --git a/0.23/references/between/index.html b/0.23/references/between/index.html index c2fcc07a..f7fe9412 100644 --- a/0.23/references/between/index.html +++ b/0.23/references/between/index.html @@ -925,8 +925,7 @@

-

If both min_val and max_val are None, -or if min_val is greater than max_val.

+

If min_val is greater than max_val.

@@ -936,7 +935,7 @@

-

If there's a type mismatch before comparison.

+

If there's a type mismatch during comparison.

@@ -947,12 +946,9 @@

Note -
-

New in version 0.2.0.

-
- +
Source code in src/validators/between.py
14
@@ -1022,24 +1018,7 @@ 

78 79 80 -81 -82 -83 -84 -85 -86 -87 -88 -89 -90 -91 -92 -93 -94 -95 -96 -97 -98

@validator
+81
@validator
 def between(
     value: PossibleValueTypes,
     /,
@@ -1085,45 +1064,28 @@ 

If `value` is not in between the given conditions. Raises: - ValueError: If both `min_val` and `max_val` are `None`, - or if `min_val` is greater than `max_val`. - TypeError: If there's a type mismatch before comparison. + (ValueError): If `min_val` is greater than `max_val`. + (TypeError): If there's a type mismatch during comparison. Note: - `PossibleValueTypes` = `TypeVar("PossibleValueTypes", int, float, str, datetime)` - - Either one of `min_val` or `max_val` must be provided. - - > *New in version 0.2.0*. + - If neither `min_val` nor `max_val` is provided, result will always be `True`. """ if value is None: return False - if min_val is max_val is None: - raise ValueError("At least one of either `min_val` or `max_val` must be specified") - if max_val is None: max_val = AbsMax() if min_val is None: min_val = AbsMin() - if isinstance(min_val, AbsMin): - if type(value) is type(max_val): - return min_val <= value <= max_val - raise TypeError("`value` and `max_val` must be of same type") - - if isinstance(max_val, AbsMax): - if type(value) is type(min_val): - return min_val <= value <= max_val - raise TypeError("`value` and `min_val` must be of same type") - - if type(min_val) is type(max_val): + try: if min_val > max_val: - raise ValueError("`min_val` cannot be more than `max_val`") - if type(value) is type(min_val): # or is type(max_val) - return min_val <= value <= max_val - raise TypeError("`value` and (`min_val` or `max_val`) must be of same type") + raise ValueError("`min_val` cannot be greater than `max_val`") + except TypeError as err: + raise TypeError("Comparison type mismatch") from err - raise TypeError("`value` and `min_val` and `max_val` must be of same type") + return min_val <= value <= max_val

diff --git a/0.23/references/btc_address.rst b/0.23/references/btc_address.rst index 6df84479..2b22e68c 100644 --- a/0.23/references/btc_address.rst +++ b/0.23/references/btc_address.rst @@ -5,3 +5,5 @@ btc_address .. autofunction:: btc_address .. module:: validators.btc_address .. autofunction:: btc_address +.. module:: validators.btc_address +.. autofunction:: btc_address diff --git a/0.23/references/card.rst b/0.23/references/card.rst index 7314b94b..181eeef6 100644 --- a/0.23/references/card.rst +++ b/0.23/references/card.rst @@ -1,6 +1,8 @@ card ---- +.. module:: validators.card +.. autofunction:: visa .. module:: validators.card .. autofunction:: amex .. module:: validators.card diff --git a/0.23/references/country_code.rst b/0.23/references/country_code.rst index f2ee2750..d2a7efad 100644 --- a/0.23/references/country_code.rst +++ b/0.23/references/country_code.rst @@ -5,3 +5,5 @@ country_code .. autofunction:: country_code .. module:: validators.country_code .. autofunction:: country_code +.. module:: validators.country_code +.. autofunction:: country_code diff --git a/0.23/references/domain.rst b/0.23/references/domain.rst index 3fe816c1..5c983271 100644 --- a/0.23/references/domain.rst +++ b/0.23/references/domain.rst @@ -5,3 +5,5 @@ domain .. autofunction:: domain .. module:: validators.domain .. autofunction:: domain +.. module:: validators.domain +.. autofunction:: domain diff --git a/0.23/references/email.rst b/0.23/references/email.rst index 7304b0b2..ce28f8dc 100644 --- a/0.23/references/email.rst +++ b/0.23/references/email.rst @@ -5,3 +5,5 @@ email .. autofunction:: email .. module:: validators.email .. autofunction:: email +.. module:: validators.email +.. autofunction:: email diff --git a/0.23/references/hashes.rst b/0.23/references/hashes.rst index 5165e287..cce4a957 100644 --- a/0.23/references/hashes.rst +++ b/0.23/references/hashes.rst @@ -1,6 +1,8 @@ hashes ------ +.. module:: validators.hashes +.. autofunction:: sha512 .. module:: validators.hashes .. autofunction:: md5 .. module:: validators.hashes diff --git a/0.23/references/hostname.rst b/0.23/references/hostname.rst index 01c599e0..2b997565 100644 --- a/0.23/references/hostname.rst +++ b/0.23/references/hostname.rst @@ -5,3 +5,5 @@ hostname .. autofunction:: hostname .. module:: validators.hostname .. autofunction:: hostname +.. module:: validators.hostname +.. autofunction:: hostname diff --git a/0.23/references/i18n.rst b/0.23/references/i18n.rst index 4f08663f..694f085e 100644 --- a/0.23/references/i18n.rst +++ b/0.23/references/i18n.rst @@ -1,6 +1,8 @@ i18n ---- +.. module:: validators.i18n +.. autofunction:: fr_ssn .. module:: validators.i18n .. autofunction:: es_cif .. module:: validators.i18n diff --git a/0.23/references/iban.rst b/0.23/references/iban.rst index 151096b1..64c5692a 100644 --- a/0.23/references/iban.rst +++ b/0.23/references/iban.rst @@ -5,3 +5,5 @@ iban .. autofunction:: iban .. module:: validators.iban .. autofunction:: iban +.. module:: validators.iban +.. autofunction:: iban diff --git a/0.23/references/ip_address.rst b/0.23/references/ip_address.rst index 82b945a9..c04985d9 100644 --- a/0.23/references/ip_address.rst +++ b/0.23/references/ip_address.rst @@ -1,6 +1,8 @@ ip_address ---------- +.. module:: validators.ip_address +.. autofunction:: ipv6 .. module:: validators.ip_address .. autofunction:: ipv4 .. module:: validators.ip_address diff --git a/0.23/references/length.rst b/0.23/references/length.rst index e0307ecd..f897e9d8 100644 --- a/0.23/references/length.rst +++ b/0.23/references/length.rst @@ -5,3 +5,5 @@ length .. autofunction:: length .. module:: validators.length .. autofunction:: length +.. module:: validators.length +.. autofunction:: length diff --git a/0.23/references/length/index.html b/0.23/references/length/index.html index 0eb6ca0e..474c9f81 100644 --- a/0.23/references/length/index.html +++ b/0.23/references/length/index.html @@ -786,7 +786,7 @@

length - validators.length.length(value, /, *, min_val=0, max_val=0) + validators.length.length(value, /, *, min_val=None, max_val=None)

@@ -836,7 +836,7 @@

min_val - int + Union[int, None]
@@ -845,13 +845,13 @@

- 0 + None max_val - int + Union[int, None]
@@ -860,7 +860,7 @@

- 0 + None @@ -899,16 +899,34 @@

-
-

New in version 0.2.0.

-
+ + + +

Raises:

+ + + + + + + + + + + + + +
TypeDescription
+ ValueError + +
+

If either min_val or max_val is negative.

+
+
Source code in src/validators/length.py -
 8
- 9
-10
-11
+            
11
 12
 13
 14
@@ -935,8 +953,17 @@ 

35 36 37 -38

@validator
-def length(value: str, /, *, min_val: int = 0, max_val: int = 0):
+38
+39
+40
+41
+42
+43
+44
+45
+46
+47
@validator
+def length(value: str, /, *, min_val: Union[int, None] = None, max_val: Union[int, None] = None):
     """Return whether or not the length of given string is within a specified range.
 
     Examples:
@@ -963,9 +990,15 @@ 

(ValidationError): If `len(value)` is not in between the given conditions. - > *New in version 0.2.0*. + Raises: + (ValueError): If either `min_val` or `max_val` is negative. """ - return between(len(value), min_val=min_val, max_val=max_val) if value else False + if min_val is not None and min_val < 0: + raise ValueError("Length cannot be negative. `min_val` is less than zero.") + if max_val is not None and max_val < 0: + raise ValueError("Length cannot be negative. `max_val` is less than zero.") + + return bool(between(len(value), min_val=min_val, max_val=max_val))

diff --git a/0.23/references/mac_address.rst b/0.23/references/mac_address.rst index e30fa6bc..22a41e28 100644 --- a/0.23/references/mac_address.rst +++ b/0.23/references/mac_address.rst @@ -5,3 +5,5 @@ mac_address .. autofunction:: mac_address .. module:: validators.mac_address .. autofunction:: mac_address +.. module:: validators.mac_address +.. autofunction:: mac_address diff --git a/0.23/references/slug.rst b/0.23/references/slug.rst index 9ddee749..da1c8f4f 100644 --- a/0.23/references/slug.rst +++ b/0.23/references/slug.rst @@ -5,3 +5,5 @@ slug .. autofunction:: slug .. module:: validators.slug .. autofunction:: slug +.. module:: validators.slug +.. autofunction:: slug diff --git a/0.23/references/url.rst b/0.23/references/url.rst index a3e92047..e2dd421a 100644 --- a/0.23/references/url.rst +++ b/0.23/references/url.rst @@ -5,3 +5,5 @@ url .. autofunction:: url .. module:: validators.url .. autofunction:: url +.. module:: validators.url +.. autofunction:: url diff --git a/0.23/references/utils.rst b/0.23/references/utils.rst index 6a5f970d..a94b7f53 100644 --- a/0.23/references/utils.rst +++ b/0.23/references/utils.rst @@ -1,6 +1,8 @@ utils ----- +.. module:: validators.utils +.. autofunction:: validator .. module:: validators.utils .. autofunction:: ValidationError .. module:: validators.utils diff --git a/0.23/references/uuid.rst b/0.23/references/uuid.rst index 08ba33be..5cd86b98 100644 --- a/0.23/references/uuid.rst +++ b/0.23/references/uuid.rst @@ -5,3 +5,5 @@ uuid .. autofunction:: uuid .. module:: validators.uuid .. autofunction:: uuid +.. module:: validators.uuid +.. autofunction:: uuid diff --git a/0.23/search/search_index.json b/0.23/search/search_index.json index 464c1533..ee4a8235 100644 --- a/0.23/search/search_index.json +++ b/0.23/search/search_index.json @@ -1 +1 @@ -{"config":{"lang":["en"],"separator":"[\\s\\-]+","pipeline":["stopWordFilter"]},"docs":[{"location":"","title":"validators - Python Data Validation for Humans\u2122","text":"

Python has all kinds of data validation tools, but every one of them seems to require defining a schema or form. I wanted to create a simple validation library where validating a simple value does not require defining a form or a schema.

>>> import validators\n>>> \n>>> validators.email('someone@example.com')\nTrue\n
"},{"location":"#resources","title":"Resources","text":"
  • Documentation
  • Bugtracker
  • Security
  • Code
"},{"location":"references/between/","title":"between","text":""},{"location":"references/between/#validators.between.between","title":"validators.between.between(value, /, *, min_val=None, max_val=None)","text":"

Validate that a number is between minimum and/or maximum value.

This will work with any comparable type, such as floats, decimals and dates not just integers. This validator is originally based on WTForms-NumberRange-Validator.

Examples:

>>> from datetime import datetime\n>>> between(5, min_val=2)\n# Output: True\n>>> between(13.2, min_val=13, max_val=14)\n# Output: True\n>>> between(500, max_val=400)\n# Output: ValidationError(func=between, args=...)\n>>> between(\n...     datetime(2000, 11, 11),\n...     min_val=datetime(1999, 11, 11)\n... )\n# Output: True\n

Parameters:

Name Type Description Default value PossibleValueTypes

Value which is to be compared.

required min_val Union[PossibleValueTypes, AbsMin, None]

The minimum required value of the number. If not provided, minimum value will not be checked.

None max_val Union[PossibleValueTypes, AbsMax, None]

The maximum value of the number. If not provided, maximum value will not be checked.

None

Returns:

Type Description Literal[True]

If value is in between the given conditions.

ValidationError

If value is not in between the given conditions.

Raises:

Type Description ValueError

If both min_val and max_val are None, or if min_val is greater than max_val.

TypeError

If there's a type mismatch before comparison.

Note
  • PossibleValueTypes = TypeVar(\"PossibleValueTypes\", int, float, str, datetime)
  • Either one of min_val or max_val must be provided.

New in version 0.2.0.

Source code in src/validators/between.py
@validator\ndef between(\n    value: PossibleValueTypes,\n    /,\n    *,\n    min_val: Union[PossibleValueTypes, AbsMin, None] = None,\n    max_val: Union[PossibleValueTypes, AbsMax, None] = None,\n):\n    \"\"\"Validate that a number is between minimum and/or maximum value.\n\n    This will work with any comparable type, such as floats, decimals and dates\n    not just integers. This validator is originally based on [WTForms-NumberRange-Validator][1].\n\n    [1]: https://github.com/wtforms/wtforms/blob/master/src/wtforms/validators.py#L166-L220\n\n    Examples:\n        >>> from datetime import datetime\n        >>> between(5, min_val=2)\n        # Output: True\n        >>> between(13.2, min_val=13, max_val=14)\n        # Output: True\n        >>> between(500, max_val=400)\n        # Output: ValidationError(func=between, args=...)\n        >>> between(\n        ...     datetime(2000, 11, 11),\n        ...     min_val=datetime(1999, 11, 11)\n        ... )\n        # Output: True\n\n    Args:\n        value:\n            Value which is to be compared.\n        min_val:\n            The minimum required value of the number.\n            If not provided, minimum value will not be checked.\n        max_val:\n            The maximum value of the number.\n            If not provided, maximum value will not be checked.\n\n    Returns:\n        (Literal[True]):\n            If `value` is in between the given conditions.\n        (ValidationError):\n            If `value` is not in between the given conditions.\n\n    Raises:\n        ValueError: If both `min_val` and `max_val` are `None`,\n            or if `min_val` is greater than `max_val`.\n        TypeError: If there's a type mismatch before comparison.\n\n    Note:\n        - `PossibleValueTypes` = `TypeVar(\"PossibleValueTypes\", int, float, str, datetime)`\n        - Either one of `min_val` or `max_val` must be provided.\n\n    > *New in version 0.2.0*.\n    \"\"\"\n    if value is None:\n        return False\n\n    if min_val is max_val is None:\n        raise ValueError(\"At least one of either `min_val` or `max_val` must be specified\")\n\n    if max_val is None:\n        max_val = AbsMax()\n    if min_val is None:\n        min_val = AbsMin()\n\n    if isinstance(min_val, AbsMin):\n        if type(value) is type(max_val):\n            return min_val <= value <= max_val\n        raise TypeError(\"`value` and `max_val` must be of same type\")\n\n    if isinstance(max_val, AbsMax):\n        if type(value) is type(min_val):\n            return min_val <= value <= max_val\n        raise TypeError(\"`value` and `min_val` must be of same type\")\n\n    if type(min_val) is type(max_val):\n        if min_val > max_val:\n            raise ValueError(\"`min_val` cannot be more than `max_val`\")\n        if type(value) is type(min_val):  # or is type(max_val)\n            return min_val <= value <= max_val\n        raise TypeError(\"`value` and (`min_val` or `max_val`) must be of same type\")\n\n    raise TypeError(\"`value` and `min_val` and `max_val` must be of same type\")\n
"},{"location":"references/btc_address/","title":"btc_address","text":""},{"location":"references/btc_address/#validators.btc_address.btc_address","title":"validators.btc_address.btc_address(value)","text":"

Return whether or not given value is a valid bitcoin address.

Full validation is implemented for P2PKH and P2SH addresses. For segwit addresses a regexp is used to provide a reasonable estimate on whether the address is valid.

Examples:

>>> btc_address('3Cwgr2g7vsi1bXDUkpEnVoRLA9w4FZfC69')\n# Output: True\n>>> btc_address('1BvBMsEYstWetqTFn5Au4m4GFg7xJaNVN2')\n# Output: ValidationError(func=btc_address, args=...)\n

Parameters:

Name Type Description Default value str

Bitcoin address string to validate.

required

Returns:

Type Description Literal[True]

If value is a valid bitcoin address.

ValidationError

If value is an invalid bitcoin address.

New in version 0.18.0.

Source code in src/validators/btc_address.py
@validator\ndef btc_address(value: str, /):\n    \"\"\"Return whether or not given value is a valid bitcoin address.\n\n    Full validation is implemented for P2PKH and P2SH addresses.\n    For segwit addresses a regexp is used to provide a reasonable\n    estimate on whether the address is valid.\n\n    Examples:\n        >>> btc_address('3Cwgr2g7vsi1bXDUkpEnVoRLA9w4FZfC69')\n        # Output: True\n        >>> btc_address('1BvBMsEYstWetqTFn5Au4m4GFg7xJaNVN2')\n        # Output: ValidationError(func=btc_address, args=...)\n\n    Args:\n        value:\n            Bitcoin address string to validate.\n\n    Returns:\n        (Literal[True]):\n            If `value` is a valid bitcoin address.\n        (ValidationError):\n            If `value` is an invalid bitcoin address.\n\n    > *New in version 0.18.0*.\n    \"\"\"\n    if not value:\n        return False\n\n    return (\n        # segwit pattern\n        re.compile(r\"^(bc|tc)[0-3][02-9ac-hj-np-z]{14,74}$\").match(value)\n        if value[:2] in (\"bc\", \"tb\")\n        else _validate_old_btc_address(value)\n    )\n
"},{"location":"references/card/","title":"card","text":""},{"location":"references/card/#validators.card.amex","title":"validators.card.amex(value)","text":"

Return whether or not given value is a valid American Express card number.

Examples:

>>> amex('378282246310005')\n# Output: True\n>>> amex('4242424242424242')\n# Output: ValidationError(func=amex, args={'value': '4242424242424242'})\n

Parameters:

Name Type Description Default value str

American Express card number string to validate

required

Returns:

Type Description Literal[True]

If value is a valid American Express card number.

ValidationError

If value is an invalid American Express card number.

New in version 0.15.0.

Source code in src/validators/card.py
@validator\ndef amex(value: str, /):\n    \"\"\"Return whether or not given value is a valid American Express card number.\n\n    Examples:\n        >>> amex('378282246310005')\n        # Output: True\n        >>> amex('4242424242424242')\n        # Output: ValidationError(func=amex, args={'value': '4242424242424242'})\n\n    Args:\n        value:\n            American Express card number string to validate\n\n    Returns:\n        (Literal[True]):\n            If `value` is a valid American Express card number.\n        (ValidationError):\n            If `value` is an invalid American Express card number.\n\n    > *New in version 0.15.0*.\n    \"\"\"\n    pattern = re.compile(r\"^(34|37)\")\n    return card_number(value) and len(value) == 15 and pattern.match(value)\n
"},{"location":"references/card/#validators.card.card_number","title":"validators.card.card_number(value)","text":"

Return whether or not given value is a valid generic card number.

This validator is based on Luhn's algorithm.

Examples:

>>> card_number('4242424242424242')\n# Output: True\n>>> card_number('4242424242424241')\n# Output: ValidationError(func=card_number, args={'value': '4242424242424241'})\n

Parameters:

Name Type Description Default value str

Generic card number string to validate

required

Returns:

Type Description Literal[True]

If value is a valid generic card number.

ValidationError

If value is an invalid generic card number.

New in version 0.15.0.

Source code in src/validators/card.py
@validator\ndef card_number(value: str, /):\n    \"\"\"Return whether or not given value is a valid generic card number.\n\n    This validator is based on [Luhn's algorithm][1].\n\n    [1]: https://github.com/mmcloughlin/luhn\n\n    Examples:\n        >>> card_number('4242424242424242')\n        # Output: True\n        >>> card_number('4242424242424241')\n        # Output: ValidationError(func=card_number, args={'value': '4242424242424241'})\n\n    Args:\n        value:\n            Generic card number string to validate\n\n    Returns:\n        (Literal[True]):\n            If `value` is a valid generic card number.\n        (ValidationError):\n            If `value` is an invalid generic card number.\n\n    > *New in version 0.15.0*.\n    \"\"\"\n    if not value:\n        return False\n    try:\n        digits = list(map(int, value))\n        odd_sum = sum(digits[-1::-2])\n        even_sum = sum(sum(divmod(2 * d, 10)) for d in digits[-2::-2])\n        return (odd_sum + even_sum) % 10 == 0\n    except ValueError:\n        return False\n
"},{"location":"references/card/#validators.card.diners","title":"validators.card.diners(value)","text":"

Return whether or not given value is a valid Diners Club card number.

Examples:

>>> diners('3056930009020004')\n# Output: True\n>>> diners('4242424242424242')\n# Output: ValidationError(func=diners, args={'value': '4242424242424242'})\n

Parameters:

Name Type Description Default value str

Diners Club card number string to validate

required

Returns:

Type Description Literal[True]

If value is a valid Diners Club card number.

ValidationError

If value is an invalid Diners Club card number.

New in version 0.15.0.

Source code in src/validators/card.py
@validator\ndef diners(value: str, /):\n    \"\"\"Return whether or not given value is a valid Diners Club card number.\n\n    Examples:\n        >>> diners('3056930009020004')\n        # Output: True\n        >>> diners('4242424242424242')\n        # Output: ValidationError(func=diners, args={'value': '4242424242424242'})\n\n    Args:\n        value:\n            Diners Club card number string to validate\n\n    Returns:\n        (Literal[True]):\n            If `value` is a valid Diners Club card number.\n        (ValidationError):\n            If `value` is an invalid Diners Club card number.\n\n    > *New in version 0.15.0*.\n    \"\"\"\n    pattern = re.compile(r\"^(30|36|38|39)\")\n    return card_number(value) and len(value) in {14, 16} and pattern.match(value)\n
"},{"location":"references/card/#validators.card.discover","title":"validators.card.discover(value)","text":"

Return whether or not given value is a valid Discover card number.

Examples:

>>> discover('6011111111111117')\n# Output: True\n>>> discover('4242424242424242')\n# Output: ValidationError(func=discover, args={'value': '4242424242424242'})\n

Parameters:

Name Type Description Default value str

Discover card number string to validate

required

Returns:

Type Description Literal[True]

If value is a valid Discover card number.

ValidationError

If value is an invalid Discover card number.

New in version 0.15.0.

Source code in src/validators/card.py
@validator\ndef discover(value: str, /):\n    \"\"\"Return whether or not given value is a valid Discover card number.\n\n    Examples:\n        >>> discover('6011111111111117')\n        # Output: True\n        >>> discover('4242424242424242')\n        # Output: ValidationError(func=discover, args={'value': '4242424242424242'})\n\n    Args:\n        value:\n            Discover card number string to validate\n\n    Returns:\n        (Literal[True]):\n            If `value` is a valid Discover card number.\n        (ValidationError):\n            If `value` is an invalid Discover card number.\n\n    > *New in version 0.15.0*.\n    \"\"\"\n    pattern = re.compile(r\"^(60|64|65)\")\n    return card_number(value) and len(value) == 16 and pattern.match(value)\n
"},{"location":"references/card/#validators.card.jcb","title":"validators.card.jcb(value)","text":"

Return whether or not given value is a valid JCB card number.

Examples:

>>> jcb('3566002020360505')\n# Output: True\n>>> jcb('4242424242424242')\n# Output: ValidationError(func=jcb, args={'value': '4242424242424242'})\n

Parameters:

Name Type Description Default value str

JCB card number string to validate

required

Returns:

Type Description Literal[True]

If value is a valid JCB card number.

ValidationError

If value is an invalid JCB card number.

New in version 0.15.0.

Source code in src/validators/card.py
@validator\ndef jcb(value: str, /):\n    \"\"\"Return whether or not given value is a valid JCB card number.\n\n    Examples:\n        >>> jcb('3566002020360505')\n        # Output: True\n        >>> jcb('4242424242424242')\n        # Output: ValidationError(func=jcb, args={'value': '4242424242424242'})\n\n    Args:\n        value:\n            JCB card number string to validate\n\n    Returns:\n        (Literal[True]):\n            If `value` is a valid JCB card number.\n        (ValidationError):\n            If `value` is an invalid JCB card number.\n\n    > *New in version 0.15.0*.\n    \"\"\"\n    pattern = re.compile(r\"^35\")\n    return card_number(value) and len(value) == 16 and pattern.match(value)\n
"},{"location":"references/card/#validators.card.mastercard","title":"validators.card.mastercard(value)","text":"

Return whether or not given value is a valid Mastercard card number.

Examples:

>>> mastercard('5555555555554444')\n# Output: True\n>>> mastercard('4242424242424242')\n# Output: ValidationError(func=mastercard, args={'value': '4242424242424242'})\n

Parameters:

Name Type Description Default value str

Mastercard card number string to validate

required

Returns:

Type Description Literal[True]

If value is a valid Mastercard card number.

ValidationError

If value is an invalid Mastercard card number.

New in version 0.15.0.

Source code in src/validators/card.py
@validator\ndef mastercard(value: str, /):\n    \"\"\"Return whether or not given value is a valid Mastercard card number.\n\n    Examples:\n        >>> mastercard('5555555555554444')\n        # Output: True\n        >>> mastercard('4242424242424242')\n        # Output: ValidationError(func=mastercard, args={'value': '4242424242424242'})\n\n    Args:\n        value:\n            Mastercard card number string to validate\n\n    Returns:\n        (Literal[True]):\n            If `value` is a valid Mastercard card number.\n        (ValidationError):\n            If `value` is an invalid Mastercard card number.\n\n    > *New in version 0.15.0*.\n    \"\"\"\n    pattern = re.compile(r\"^(51|52|53|54|55|22|23|24|25|26|27)\")\n    return card_number(value) and len(value) == 16 and pattern.match(value)\n
"},{"location":"references/card/#validators.card.unionpay","title":"validators.card.unionpay(value)","text":"

Return whether or not given value is a valid UnionPay card number.

Examples:

>>> unionpay('6200000000000005')\n# Output: True\n>>> unionpay('4242424242424242')\n# Output: ValidationError(func=unionpay, args={'value': '4242424242424242'})\n

Parameters:

Name Type Description Default value str

UnionPay card number string to validate

required

Returns:

Type Description Literal[True]

If value is a valid UnionPay card number.

ValidationError

If value is an invalid UnionPay card number.

New in version 0.15.0.

Source code in src/validators/card.py
@validator\ndef unionpay(value: str, /):\n    \"\"\"Return whether or not given value is a valid UnionPay card number.\n\n    Examples:\n        >>> unionpay('6200000000000005')\n        # Output: True\n        >>> unionpay('4242424242424242')\n        # Output: ValidationError(func=unionpay, args={'value': '4242424242424242'})\n\n    Args:\n        value:\n            UnionPay card number string to validate\n\n    Returns:\n        (Literal[True]):\n            If `value` is a valid UnionPay card number.\n        (ValidationError):\n            If `value` is an invalid UnionPay card number.\n\n    > *New in version 0.15.0*.\n    \"\"\"\n    pattern = re.compile(r\"^62\")\n    return card_number(value) and len(value) == 16 and pattern.match(value)\n
"},{"location":"references/card/#validators.card.visa","title":"validators.card.visa(value)","text":"

Return whether or not given value is a valid Visa card number.

Examples:

>>> visa('4242424242424242')\n# Output: True\n>>> visa('2223003122003222')\n# Output: ValidationError(func=visa, args={'value': '2223003122003222'})\n

Parameters:

Name Type Description Default value str

Visa card number string to validate

required

Returns:

Type Description Literal[True]

If value is a valid Visa card number.

ValidationError

If value is an invalid Visa card number.

New in version 0.15.0.

Source code in src/validators/card.py
@validator\ndef visa(value: str, /):\n    \"\"\"Return whether or not given value is a valid Visa card number.\n\n    Examples:\n        >>> visa('4242424242424242')\n        # Output: True\n        >>> visa('2223003122003222')\n        # Output: ValidationError(func=visa, args={'value': '2223003122003222'})\n\n    Args:\n        value:\n            Visa card number string to validate\n\n    Returns:\n        (Literal[True]):\n            If `value` is a valid Visa card number.\n        (ValidationError):\n            If `value` is an invalid Visa card number.\n\n    > *New in version 0.15.0*.\n    \"\"\"\n    pattern = re.compile(r\"^4\")\n    return card_number(value) and len(value) == 16 and pattern.match(value)\n
"},{"location":"references/country_code/","title":"country_code","text":""},{"location":"references/country_code/#validators.country_code.country_code","title":"validators.country_code.country_code(value, /, *, iso_format='auto')","text":"

Validates given country code.

This performs a case-sensitive ISO 3166 country code validation.

Examples:

>>> country_code('GB', iso_format='alpha3')\n# Output: False\n>>> country_code('USA')\n# Output: True\n>>> country_code('840', iso_format='numeric')\n# Output: True\n>>> country_code('iN', iso_format='alpha2')\n# Output: False\n>>> country_code('ZWE', iso_format='alpha3')\n# Output: True\n

Parameters:

Name Type Description Default value str

Country code string to validate.

required iso_format str

ISO format to be used. Available options are: auto, alpha2, alpha3 and numeric.

'auto'

Returns:

Type Description Literal[True]

If value is a valid country code.

ValidationError

If value is an invalid country code.

Source code in src/validators/country_code.py
@validator\ndef country_code(value: str, /, *, iso_format: str = \"auto\"):\n    \"\"\"Validates given country code.\n\n    This performs a case-sensitive [ISO 3166][1] country code validation.\n\n    [1]: https://www.iso.org/iso-3166-country-codes.html\n\n    Examples:\n        >>> country_code('GB', iso_format='alpha3')\n        # Output: False\n        >>> country_code('USA')\n        # Output: True\n        >>> country_code('840', iso_format='numeric')\n        # Output: True\n        >>> country_code('iN', iso_format='alpha2')\n        # Output: False\n        >>> country_code('ZWE', iso_format='alpha3')\n        # Output: True\n\n    Args:\n        value:\n            Country code string to validate.\n        iso_format:\n            ISO format to be used. Available options are:\n            `auto`, `alpha2`, `alpha3` and `numeric`.\n\n    Returns:\n        (Literal[True]):\n            If `value` is a valid country code.\n        (ValidationError):\n            If `value` is an invalid country code.\n    \"\"\"\n    if not value:\n        return False\n\n    if not (1 < len(value) < 4):\n        return False\n\n    if iso_format == \"auto\" and (iso_format := get_code_type(value)) == \"invalid\":\n        return False\n\n    if iso_format == \"alpha2\":\n        return value in alpha_2\n    if iso_format == \"alpha3\":\n        return value in alpha_3\n    return value in numeric if iso_format == \"numeric\" else False\n
"},{"location":"references/domain/","title":"domain","text":""},{"location":"references/domain/#validators.domain.domain","title":"validators.domain.domain(value, /, *, rfc_1034=False, rfc_2782=False)","text":"

Return whether or not given value is a valid domain.

Examples:

>>> domain('example.com')\n# Output: True\n>>> domain('example.com/')\n# Output: ValidationError(func=domain, ...)\n>>> # Supports IDN domains as well::\n>>> domain('xn----gtbspbbmkef.xn--p1ai')\n# Output: True\n

Parameters:

Name Type Description Default value str

Domain string to validate.

required rfc_1034 bool

Allow trailing dot in domain name. Ref: RFC 1034.

False rfc_2782 bool

Domain name is of type service record. Ref: RFC 2782.

False

Returns:

Type Description Literal[True]

If value is a valid domain name.

ValidationError

If value is an invalid domain name.

Note
  • In version 0.10.0:
    • Added support for internationalized domain name (IDN) validation.

New in version 0.9.0.

Source code in src/validators/domain.py
@validator\ndef domain(value: str, /, *, rfc_1034: bool = False, rfc_2782: bool = False):\n    \"\"\"Return whether or not given value is a valid domain.\n\n    Examples:\n        >>> domain('example.com')\n        # Output: True\n        >>> domain('example.com/')\n        # Output: ValidationError(func=domain, ...)\n        >>> # Supports IDN domains as well::\n        >>> domain('xn----gtbspbbmkef.xn--p1ai')\n        # Output: True\n\n    Args:\n        value:\n            Domain string to validate.\n        rfc_1034:\n            Allow trailing dot in domain name.\n            Ref: [RFC 1034](https://www.rfc-editor.org/rfc/rfc1034).\n        rfc_2782:\n            Domain name is of type service record.\n            Ref: [RFC 2782](https://www.rfc-editor.org/rfc/rfc2782).\n\n\n    Returns:\n        (Literal[True]):\n            If `value` is a valid domain name.\n        (ValidationError):\n            If `value` is an invalid domain name.\n\n    Note:\n        - *In version 0.10.0*:\n            - Added support for internationalized domain name (IDN) validation.\n\n    > *New in version 0.9.0*.\n    \"\"\"\n    if not value:\n        return False\n    try:\n        return not re.search(r\"\\s\", value) and re.match(\n            # First character of the domain\n            rf\"^(?:[a-zA-Z0-9{'_'if rfc_2782 else ''}]\"\n            # Sub domain + hostname\n            + r\"(?:[a-zA-Z0-9-_]{0,61}[A-Za-z0-9])?\\.)\"\n            # First 61 characters of the gTLD\n            + r\"+[A-Za-z0-9][A-Za-z0-9-_]{0,61}\"\n            # Last character of the gTLD\n            + rf\"[A-Za-z]{r'.$' if rfc_1034 else r'$'}\",\n            value.encode(\"idna\").decode(\"utf-8\"),\n            re.IGNORECASE,\n        )\n    except UnicodeError:\n        return False\n
"},{"location":"references/email/","title":"email","text":""},{"location":"references/email/#validators.email.email","title":"validators.email.email(value, /, *, ipv6_address=False, ipv4_address=False, simple_host=False, rfc_1034=False, rfc_2782=False)","text":"

Validate an email address.

This was inspired from Django's email validator. Also ref: RFC 1034, RFC 5321 and RFC 5322.

Examples:

>>> email('someone@example.com')\n# Output: True\n>>> email('bogus@@')\n# Output: ValidationError(email=email, args={'value': 'bogus@@'})\n

Parameters:

Name Type Description Default value str

eMail string to validate.

required ipv6_address bool

When the domain part is an IPv6 address.

False ipv4_address bool

When the domain part is an IPv4 address.

False simple_host bool

When the domain part is a simple hostname.

False rfc_1034 bool

Allow trailing dot in domain name. Ref: RFC 1034.

False rfc_2782 bool

Domain name is of type service record. Ref: RFC 2782.

False

Returns:

Type Description Literal[True]

If value is a valid eMail.

ValidationError

If value is an invalid eMail.

New in version 0.1.0.

Source code in src/validators/email.py
@validator\ndef email(\n    value: str,\n    /,\n    *,\n    ipv6_address: bool = False,\n    ipv4_address: bool = False,\n    simple_host: bool = False,\n    rfc_1034: bool = False,\n    rfc_2782: bool = False,\n):\n    \"\"\"Validate an email address.\n\n    This was inspired from [Django's email validator][1].\n    Also ref: [RFC 1034][2], [RFC 5321][3] and [RFC 5322][4].\n\n    [1]: https://github.com/django/django/blob/main/django/core/validators.py#L174\n    [2]: https://www.rfc-editor.org/rfc/rfc1034\n    [3]: https://www.rfc-editor.org/rfc/rfc5321\n    [4]: https://www.rfc-editor.org/rfc/rfc5322\n\n    Examples:\n        >>> email('someone@example.com')\n        # Output: True\n        >>> email('bogus@@')\n        # Output: ValidationError(email=email, args={'value': 'bogus@@'})\n\n    Args:\n        value:\n            eMail string to validate.\n        ipv6_address:\n            When the domain part is an IPv6 address.\n        ipv4_address:\n            When the domain part is an IPv4 address.\n        simple_host:\n            When the domain part is a simple hostname.\n        rfc_1034:\n            Allow trailing dot in domain name.\n            Ref: [RFC 1034](https://www.rfc-editor.org/rfc/rfc1034).\n        rfc_2782:\n            Domain name is of type service record.\n            Ref: [RFC 2782](https://www.rfc-editor.org/rfc/rfc2782).\n\n    Returns:\n        (Literal[True]):\n            If `value` is a valid eMail.\n        (ValidationError):\n            If `value` is an invalid eMail.\n\n    > *New in version 0.1.0*.\n    \"\"\"\n    if not value or value.count(\"@\") != 1:\n        return False\n\n    username_part, domain_part = value.rsplit(\"@\", 1)\n\n    if len(username_part) > 64 or len(domain_part) > 253:\n        # ref: RFC 1034 and 5231\n        return False\n\n    if ipv6_address or ipv4_address:\n        if domain_part.startswith(\"[\") and domain_part.endswith(\"]\"):\n            # ref: RFC 5321\n            domain_part = domain_part.lstrip(\"[\").rstrip(\"]\")\n        else:\n            return False\n\n    return (\n        bool(\n            hostname(\n                domain_part,\n                skip_ipv6_addr=not ipv6_address,\n                skip_ipv4_addr=not ipv4_address,\n                may_have_port=False,\n                maybe_simple=simple_host,\n                rfc_1034=rfc_1034,\n                rfc_2782=rfc_2782,\n            )\n        )\n        if re.match(\n            # dot-atom\n            r\"(^[-!#$%&'*+/=?^_`{}|~0-9A-Z]+(\\.[-!#$%&'*+/=?^_`{}|~0-9A-Z]+)*$\"\n            # quoted-string\n            + r'|^\"([\\001-\\010\\013\\014\\016-\\037!#-\\[\\]-\\177]|\\\\[\\001-\\011\\013\\014\\016-\\177])*\"$)',\n            username_part,\n            re.IGNORECASE,\n        )\n        else False\n    )\n
"},{"location":"references/hashes/","title":"hashes","text":""},{"location":"references/hashes/#validators.hashes.md5","title":"validators.hashes.md5(value)","text":"

Return whether or not given value is a valid MD5 hash.

Examples:

>>> md5('d41d8cd98f00b204e9800998ecf8427e')\n# Output: True\n>>> md5('900zz11')\n# Output: ValidationError(func=md5, args={'value': '900zz11'})\n

Parameters:

Name Type Description Default value str

MD5 string to validate.

required

Returns:

Type Description Literal[True]

If value is a valid MD5 hash.

ValidationError

If value is an invalid MD5 hash.

New in version 0.12.1

Source code in src/validators/hashes.py
@validator\ndef md5(value: str, /):\n    \"\"\"Return whether or not given value is a valid MD5 hash.\n\n    Examples:\n        >>> md5('d41d8cd98f00b204e9800998ecf8427e')\n        # Output: True\n        >>> md5('900zz11')\n        # Output: ValidationError(func=md5, args={'value': '900zz11'})\n\n    Args:\n        value:\n            MD5 string to validate.\n\n    Returns:\n        (Literal[True]):\n            If `value` is a valid MD5 hash.\n        (ValidationError):\n            If `value` is an invalid MD5 hash.\n\n    > *New in version 0.12.1*\n    \"\"\"\n    return re.match(r\"^[0-9a-f]{32}$\", value, re.IGNORECASE) if value else False\n
"},{"location":"references/hashes/#validators.hashes.sha1","title":"validators.hashes.sha1(value)","text":"

Return whether or not given value is a valid SHA1 hash.

Examples:

>>> sha1('da39a3ee5e6b4b0d3255bfef95601890afd80709')\n# Output: True\n>>> sha1('900zz11')\n# Output: ValidationError(func=sha1, args={'value': '900zz11'})\n

Parameters:

Name Type Description Default value str

SHA1 string to validate.

required

Returns:

Type Description Literal[True]

If value is a valid SHA1 hash.

ValidationError

If value is an invalid SHA1 hash.

New in version 0.12.1

Source code in src/validators/hashes.py
@validator\ndef sha1(value: str, /):\n    \"\"\"Return whether or not given value is a valid SHA1 hash.\n\n    Examples:\n        >>> sha1('da39a3ee5e6b4b0d3255bfef95601890afd80709')\n        # Output: True\n        >>> sha1('900zz11')\n        # Output: ValidationError(func=sha1, args={'value': '900zz11'})\n\n    Args:\n        value:\n            SHA1 string to validate.\n\n    Returns:\n        (Literal[True]):\n            If `value` is a valid SHA1 hash.\n        (ValidationError):\n            If `value` is an invalid SHA1 hash.\n\n    > *New in version 0.12.1*\n    \"\"\"\n    return re.match(r\"^[0-9a-f]{40}$\", value, re.IGNORECASE) if value else False\n
"},{"location":"references/hashes/#validators.hashes.sha224","title":"validators.hashes.sha224(value)","text":"

Return whether or not given value is a valid SHA224 hash.

Examples:

>>> sha224('d14a028c2a3a2bc9476102bb288234c415a2b01f828ea62ac5b3e42f')\n# Output: True\n>>> sha224('900zz11')\n# Output: ValidationError(func=sha224, args={'value': '900zz11'})\n

Parameters:

Name Type Description Default value str

SHA224 string to validate.

required

Returns:

Type Description Literal[True]

If value is a valid SHA224 hash.

ValidationError

If value is an invalid SHA224 hash.

New in version 0.12.1

Source code in src/validators/hashes.py
@validator\ndef sha224(value: str, /):\n    \"\"\"Return whether or not given value is a valid SHA224 hash.\n\n    Examples:\n        >>> sha224('d14a028c2a3a2bc9476102bb288234c415a2b01f828ea62ac5b3e42f')\n        # Output: True\n        >>> sha224('900zz11')\n        # Output: ValidationError(func=sha224, args={'value': '900zz11'})\n\n    Args:\n        value:\n            SHA224 string to validate.\n\n    Returns:\n        (Literal[True]):\n            If `value` is a valid SHA224 hash.\n        (ValidationError):\n            If `value` is an invalid SHA224 hash.\n\n    > *New in version 0.12.1*\n    \"\"\"\n    return re.match(r\"^[0-9a-f]{56}$\", value, re.IGNORECASE) if value else False\n
"},{"location":"references/hashes/#validators.hashes.sha256","title":"validators.hashes.sha256(value)","text":"

Return whether or not given value is a valid SHA256 hash.

Examples:

>>> sha256(\n...     'e3b0c44298fc1c149afbf4c8996fb924'\n...     '27ae41e4649b934ca495991b7852b855'\n... )\n# Output: True\n>>> sha256('900zz11')\n# Output: ValidationError(func=sha256, args={'value': '900zz11'})\n

Parameters:

Name Type Description Default value str

SHA256 string to validate.

required

Returns:

Type Description Literal[True]

If value is a valid SHA256 hash.

ValidationError

If value is an invalid SHA256 hash.

New in version 0.12.1

Source code in src/validators/hashes.py
@validator\ndef sha256(value: str, /):\n    \"\"\"Return whether or not given value is a valid SHA256 hash.\n\n    Examples:\n        >>> sha256(\n        ...     'e3b0c44298fc1c149afbf4c8996fb924'\n        ...     '27ae41e4649b934ca495991b7852b855'\n        ... )\n        # Output: True\n        >>> sha256('900zz11')\n        # Output: ValidationError(func=sha256, args={'value': '900zz11'})\n\n    Args:\n        value:\n            SHA256 string to validate.\n\n    Returns:\n        (Literal[True]):\n            If `value` is a valid SHA256 hash.\n        (ValidationError):\n            If `value` is an invalid SHA256 hash.\n\n    > *New in version 0.12.1*\n    \"\"\"\n    return re.match(r\"^[0-9a-f]{64}$\", value, re.IGNORECASE) if value else False\n
"},{"location":"references/hashes/#validators.hashes.sha512","title":"validators.hashes.sha512(value)","text":"

Return whether or not given value is a valid SHA512 hash.

Examples:

>>> sha512(\n...     'cf83e1357eefb8bdf1542850d66d8007d620e4050b5715dc83f4a921d36ce'\n...     '9ce47d0d13c5d85f2b0ff8318d2877eec2f63b931bd47417a81a538327af9'\n...     '27da3e'\n... )\n# Output: True\n>>> sha512('900zz11')\n# Output: ValidationError(func=sha512, args={'value': '900zz11'})\n

Parameters:

Name Type Description Default value str

SHA512 string to validate.

required

Returns:

Type Description Literal[True]

If value is a valid SHA512 hash.

ValidationError

If value is an invalid SHA512 hash.

New in version 0.12.1

Source code in src/validators/hashes.py
@validator\ndef sha512(value: str, /):\n    \"\"\"Return whether or not given value is a valid SHA512 hash.\n\n    Examples:\n        >>> sha512(\n        ...     'cf83e1357eefb8bdf1542850d66d8007d620e4050b5715dc83f4a921d36ce'\n        ...     '9ce47d0d13c5d85f2b0ff8318d2877eec2f63b931bd47417a81a538327af9'\n        ...     '27da3e'\n        ... )\n        # Output: True\n        >>> sha512('900zz11')\n        # Output: ValidationError(func=sha512, args={'value': '900zz11'})\n\n    Args:\n        value:\n            SHA512 string to validate.\n\n    Returns:\n        (Literal[True]):\n            If `value` is a valid SHA512 hash.\n        (ValidationError):\n            If `value` is an invalid SHA512 hash.\n\n    > *New in version 0.12.1*\n    \"\"\"\n    return re.match(r\"^[0-9a-f]{128}$\", value, re.IGNORECASE) if value else False\n
"},{"location":"references/hostname/","title":"hostname","text":""},{"location":"references/hostname/#validators.hostname.hostname","title":"validators.hostname.hostname(value, /, *, skip_ipv6_addr=False, skip_ipv4_addr=False, may_have_port=True, maybe_simple=True, rfc_1034=False, rfc_2782=False)","text":"

Return whether or not given value is a valid hostname.

Examples:

>>> hostname(\"ubuntu-pc:443\")\n# Output: True\n>>> hostname(\"this-pc\")\n# Output: True\n>>> hostname(\"xn----gtbspbbmkef.xn--p1ai:65535\")\n# Output: True\n>>> hostname(\"_example.com\")\n# Output: True\n>>> hostname(\"123.5.77.88:31000\")\n# Output: True\n>>> hostname(\"12.12.12.12\")\n# Output: True\n>>> hostname(\"[::1]:22\")\n# Output: True\n>>> hostname(\"dead:beef:0:0:0:0000:42:1\")\n# Output: True\n>>> hostname(\"[0:0:0:0:0:ffff:1.2.3.4]:-65538\")\n# Output: ValidationError(func=hostname, ...)\n>>> hostname(\"[0:&:b:c:@:e:f::]:9999\")\n# Output: ValidationError(func=hostname, ...)\n

Parameters:

Name Type Description Default value str

Hostname string to validate.

required skip_ipv6_addr bool

When hostname string cannot be an IPv6 address.

False skip_ipv4_addr bool

When hostname string cannot be an IPv4 address.

False may_have_port bool

Hostname string may contain port number.

True maybe_simple bool

Hostname string maybe only hyphens and alpha-numerals.

True rfc_1034 bool

Allow trailing dot in domain/host name. Ref: RFC 1034.

False rfc_2782 bool

Domain/Host name is of type service record. Ref: RFC 2782.

False

Returns:

Type Description Literal[True]

If value is a valid hostname.

ValidationError

If value is an invalid hostname.

New in version 0.21.0.

Source code in src/validators/hostname.py
@validator\ndef hostname(\n    value: str,\n    /,\n    *,\n    skip_ipv6_addr: bool = False,\n    skip_ipv4_addr: bool = False,\n    may_have_port: bool = True,\n    maybe_simple: bool = True,\n    rfc_1034: bool = False,\n    rfc_2782: bool = False,\n):\n    \"\"\"Return whether or not given value is a valid hostname.\n\n    Examples:\n        >>> hostname(\"ubuntu-pc:443\")\n        # Output: True\n        >>> hostname(\"this-pc\")\n        # Output: True\n        >>> hostname(\"xn----gtbspbbmkef.xn--p1ai:65535\")\n        # Output: True\n        >>> hostname(\"_example.com\")\n        # Output: True\n        >>> hostname(\"123.5.77.88:31000\")\n        # Output: True\n        >>> hostname(\"12.12.12.12\")\n        # Output: True\n        >>> hostname(\"[::1]:22\")\n        # Output: True\n        >>> hostname(\"dead:beef:0:0:0:0000:42:1\")\n        # Output: True\n        >>> hostname(\"[0:0:0:0:0:ffff:1.2.3.4]:-65538\")\n        # Output: ValidationError(func=hostname, ...)\n        >>> hostname(\"[0:&:b:c:@:e:f::]:9999\")\n        # Output: ValidationError(func=hostname, ...)\n\n    Args:\n        value:\n            Hostname string to validate.\n        skip_ipv6_addr:\n            When hostname string cannot be an IPv6 address.\n        skip_ipv4_addr:\n            When hostname string cannot be an IPv4 address.\n        may_have_port:\n            Hostname string may contain port number.\n        maybe_simple:\n            Hostname string maybe only hyphens and alpha-numerals.\n        rfc_1034:\n            Allow trailing dot in domain/host name.\n            Ref: [RFC 1034](https://www.rfc-editor.org/rfc/rfc1034).\n        rfc_2782:\n            Domain/Host name is of type service record.\n            Ref: [RFC 2782](https://www.rfc-editor.org/rfc/rfc2782).\n\n    Returns:\n        (Literal[True]):\n            If `value` is a valid hostname.\n        (ValidationError):\n            If `value` is an invalid hostname.\n\n    > *New in version 0.21.0*.\n    \"\"\"\n    if not value:\n        return False\n\n    if may_have_port and (host_seg := _port_validator(value)):\n        return (\n            (_simple_hostname_regex().match(host_seg) if maybe_simple else False)\n            or domain(host_seg, rfc_1034=rfc_1034, rfc_2782=rfc_2782)\n            or (False if skip_ipv4_addr else ipv4(host_seg, cidr=False))\n            or (False if skip_ipv6_addr else ipv6(host_seg, cidr=False))\n        )\n\n    return (\n        (_simple_hostname_regex().match(value) if maybe_simple else False)\n        or domain(value, rfc_1034=rfc_1034, rfc_2782=rfc_2782)\n        or (False if skip_ipv4_addr else ipv4(value, cidr=False))\n        or (False if skip_ipv6_addr else ipv6(value, cidr=False))\n    )\n
"},{"location":"references/i18n/","title":"i18n","text":""},{"location":"references/i18n/#validators.i18n.es_cif","title":"validators.i18n.es_cif(value)","text":"

Validate a Spanish CIF.

Each company in Spain prior to 2008 had a distinct CIF and has been discontinued. For more information see wikipedia.org/cif.

The new replacement is to use NIF for absolutely everything. The issue is that there are \"types\" of NIFs now: company, person [citizen or resident] all distinguished by the first character of the DOI. For this reason we will continue to call CIFs NIFs, that are used for companies.

This validator is based on generadordni.es.

Examples:

>>> es_cif('B25162520')\n# Output: True\n>>> es_cif('B25162529')\n# Output: ValidationError(func=es_cif, args=...)\n

Parameters:

Name Type Description Default value str

DOI string which is to be validated.

required

Returns:

Type Description Literal[True]

If value is a valid DOI string.

ValidationError

If value is an invalid DOI string.

New in version 0.13.0.

Source code in src/validators/i18n/es.py
@validator\ndef es_cif(value: str, /):\n    \"\"\"Validate a Spanish CIF.\n\n    Each company in Spain prior to 2008 had a distinct CIF and has been\n    discontinued. For more information see [wikipedia.org/cif][1].\n\n    The new replacement is to use NIF for absolutely everything. The issue is\n    that there are \"types\" of NIFs now: company, person [citizen or resident]\n    all distinguished by the first character of the DOI. For this reason we\n    will continue to call CIFs NIFs, that are used for companies.\n\n    This validator is based on [generadordni.es][2].\n\n    [1]: https://es.wikipedia.org/wiki/C%C3%B3digo_de_identificaci%C3%B3n_fiscal\n    [2]: https://generadordni.es/\n\n    Examples:\n        >>> es_cif('B25162520')\n        # Output: True\n        >>> es_cif('B25162529')\n        # Output: ValidationError(func=es_cif, args=...)\n\n    Args:\n        value:\n            DOI string which is to be validated.\n\n    Returns:\n        (Literal[True]):\n            If `value` is a valid DOI string.\n        (ValidationError):\n            If `value` is an invalid DOI string.\n\n    > *New in version 0.13.0*.\n    \"\"\"\n    if not value or len(value) != 9:\n        return False\n    value = value.upper()\n    table = \"JABCDEFGHI\"\n    first_chr = value[0]\n    doi_body = value[1:8]\n    control = value[8]\n    if not doi_body.isdigit():\n        return False\n    res = (\n        10\n        - sum(\n            # Multiply each positionally even doi\n            # digit by 2 and sum it all together\n            sum(map(int, str(int(char) * 2))) if index % 2 == 0 else int(char)\n            for index, char in enumerate(doi_body)\n        )\n        % 10\n    ) % 10\n    if first_chr in \"ABEH\":  # Number type\n        return str(res) == control\n    if first_chr in \"PSQW\":  # Letter type\n        return table[res] == control\n    return control in {str(res), table[res]} if first_chr in \"CDFGJNRUV\" else False\n
"},{"location":"references/i18n/#validators.i18n.es_doi","title":"validators.i18n.es_doi(value)","text":"

Validate a Spanish DOI.

A DOI in spain is all NIF / CIF / NIE / DNI -- a digital ID. For more information see wikipedia.org/doi. This validator is based on generadordni.es.

Examples:

>>> es_doi('X0095892M')\n# Output: True\n>>> es_doi('X0095892X')\n# Output: ValidationError(func=es_doi, args=...)\n

Parameters:

Name Type Description Default value str

DOI string which is to be validated.

required

Returns:

Type Description Literal[True]

If value is a valid DOI string.

ValidationError

If value is an invalid DOI string.

New in version 0.13.0.

Source code in src/validators/i18n/es.py
@validator\ndef es_doi(value: str, /):\n    \"\"\"Validate a Spanish DOI.\n\n    A DOI in spain is all NIF / CIF / NIE / DNI -- a digital ID.\n    For more information see [wikipedia.org/doi][1]. This validator\n    is based on [generadordni.es][2].\n\n    [1]: https://es.wikipedia.org/wiki/Identificador_de_objeto_digital\n    [2]: https://generadordni.es/\n\n    Examples:\n        >>> es_doi('X0095892M')\n        # Output: True\n        >>> es_doi('X0095892X')\n        # Output: ValidationError(func=es_doi, args=...)\n\n    Args:\n        value:\n            DOI string which is to be validated.\n\n    Returns:\n        (Literal[True]):\n            If `value` is a valid DOI string.\n        (ValidationError):\n            If `value` is an invalid DOI string.\n\n    > *New in version 0.13.0*.\n    \"\"\"\n    return es_nie(value) or es_nif(value) or es_cif(value)\n
"},{"location":"references/i18n/#validators.i18n.es_nie","title":"validators.i18n.es_nie(value)","text":"

Validate a Spanish NIE.

The NIE is a tax identification number in Spain, known in Spanish as the NIE, or more formally the N\u00famero de identidad de extranjero. For more information see wikipedia.org/nie. This validator is based on generadordni.es.

Examples:

>>> es_nie('X0095892M')\n# Output: True\n>>> es_nie('X0095892X')\n# Output: ValidationError(func=es_nie, args=...)\n

Parameters:

Name Type Description Default value str

DOI string which is to be validated.

required

Returns:

Type Description Literal[True]

If value is a valid DOI string.

ValidationError

If value is an invalid DOI string.

New in version 0.13.0.

Source code in src/validators/i18n/es.py
@validator\ndef es_nie(value: str, /):\n    \"\"\"Validate a Spanish NIE.\n\n    The NIE is a tax identification number in Spain, known in Spanish\n    as the NIE, or more formally the N\u00famero de identidad de extranjero.\n    For more information see [wikipedia.org/nie][1]. This validator\n    is based on [generadordni.es][2].\n\n    [1]: https://es.wikipedia.org/wiki/N%C3%BAmero_de_identidad_de_extranjero\n    [2]: https://generadordni.es/\n\n    Examples:\n        >>> es_nie('X0095892M')\n        # Output: True\n        >>> es_nie('X0095892X')\n        # Output: ValidationError(func=es_nie, args=...)\n\n    Args:\n        value:\n            DOI string which is to be validated.\n\n    Returns:\n        (Literal[True]):\n            If `value` is a valid DOI string.\n        (ValidationError):\n            If `value` is an invalid DOI string.\n\n    > *New in version 0.13.0*.\n    \"\"\"\n    number_by_letter = {\"X\": \"0\", \"Y\": \"1\", \"Z\": \"2\"}\n    # NIE must must start with X Y or Z\n    if value and value[0] in number_by_letter:\n        return _nif_nie_validation(value, number_by_letter, {\"X0000000T\"})\n    return False\n
"},{"location":"references/i18n/#validators.i18n.es_nif","title":"validators.i18n.es_nif(value)","text":"

Validate a Spanish NIF.

Each entity, be it person or company in Spain has a distinct NIF. Since we've designated CIF to be a company NIF, this NIF is only for person. For more information see wikipedia.org/nif. This validator is based on generadordni.es.

Examples:

>>> es_nif('26643189N')\n# Output: True\n>>> es_nif('26643189X')\n# Output: ValidationError(func=es_nif, args=...)\n

Parameters:

Name Type Description Default value str

DOI string which is to be validated.

required

Returns:

Type Description Literal[True]

If value is a valid DOI string.

ValidationError

If value is an invalid DOI string.

New in version 0.13.0.

Source code in src/validators/i18n/es.py
@validator\ndef es_nif(value: str, /):\n    \"\"\"Validate a Spanish NIF.\n\n    Each entity, be it person or company in Spain has a distinct NIF. Since\n    we've designated CIF to be a company NIF, this NIF is only for person.\n    For more information see [wikipedia.org/nif][1]. This validator\n    is based on [generadordni.es][2].\n\n    [1]: https://es.wikipedia.org/wiki/N%C3%BAmero_de_identificaci%C3%B3n_fiscal\n    [2]: https://generadordni.es/\n\n    Examples:\n        >>> es_nif('26643189N')\n        # Output: True\n        >>> es_nif('26643189X')\n        # Output: ValidationError(func=es_nif, args=...)\n\n    Args:\n        value:\n            DOI string which is to be validated.\n\n    Returns:\n        (Literal[True]):\n            If `value` is a valid DOI string.\n        (ValidationError):\n            If `value` is an invalid DOI string.\n\n    > *New in version 0.13.0*.\n    \"\"\"\n    number_by_letter = {\"L\": \"0\", \"M\": \"0\", \"K\": \"0\"}\n    special_cases = {\"X0000000T\", \"00000000T\", \"00000001R\"}\n    return _nif_nie_validation(value, number_by_letter, special_cases)\n
"},{"location":"references/i18n/#validators.i18n.fi_business_id","title":"validators.i18n.fi_business_id(value)","text":"

Validate a Finnish Business ID.

Each company in Finland has a distinct business id. For more information see Finnish Trade Register

Examples:

>>> fi_business_id('0112038-9')  # Fast Monkeys Ltd\n# Output: True\n>>> fi_business_id('1234567-8')  # Bogus ID\n# Output: ValidationError(func=fi_business_id, ...)\n

Parameters:

Name Type Description Default value str

Business ID string to be validated.

required

Returns:

Type Description Literal[True]

If value is a valid finnish business id.

ValidationError

If value is an invalid finnish business id.

Note
  • In version 0.5.0:
    • Function renamed from finnish_business_id to fi_business_id

New in version 0.4.0.

Source code in src/validators/i18n/fi.py
@validator\ndef fi_business_id(value: str, /):\n    \"\"\"Validate a Finnish Business ID.\n\n    Each company in Finland has a distinct business id. For more\n    information see [Finnish Trade Register][1]\n\n    [1]: http://en.wikipedia.org/wiki/Finnish_Trade_Register\n\n    Examples:\n        >>> fi_business_id('0112038-9')  # Fast Monkeys Ltd\n        # Output: True\n        >>> fi_business_id('1234567-8')  # Bogus ID\n        # Output: ValidationError(func=fi_business_id, ...)\n\n    Args:\n        value:\n            Business ID string to be validated.\n\n    Returns:\n        (Literal[True]):\n            If `value` is a valid finnish business id.\n        (ValidationError):\n            If `value` is an invalid finnish business id.\n\n    Note:\n        - *In version 0.5.0*:\n            - Function renamed from `finnish_business_id` to `fi_business_id`\n\n    > *New in version 0.4.0*.\n    \"\"\"\n    if not value:\n        return False\n    if not re.match(_business_id_pattern(), value):\n        return False\n    factors = [7, 9, 10, 5, 8, 4, 2]\n    numbers = map(int, value[:7])\n    checksum = int(value[8])\n    modulo = sum(f * n for f, n in zip(factors, numbers)) % 11\n    return (11 - modulo == checksum) or (modulo == checksum == 0)\n
"},{"location":"references/i18n/#validators.i18n.fi_ssn","title":"validators.i18n.fi_ssn(value, /, *, allow_temporal_ssn=True)","text":"

Validate a Finnish Social Security Number.

This validator is based on django-localflavor-fi.

Examples:

>>> fi_ssn('010101-0101')\n# Output: True\n>>> fi_ssn('101010-0102')\n# Output: ValidationError(func=fi_ssn, args=...)\n

Parameters:

Name Type Description Default value str

Social Security Number to be validated.

required allow_temporal_ssn bool

Whether to accept temporal SSN numbers. Temporal SSN numbers are the ones where the serial is in the range [900-999]. By default temporal SSN numbers are valid.

True

Returns:

Type Description Literal[True]

If value is a valid finnish SSN.

ValidationError

If value is an invalid finnish SSN.

New in version 0.5.0.

Source code in src/validators/i18n/fi.py
@validator\ndef fi_ssn(value: str, /, *, allow_temporal_ssn: bool = True):\n    \"\"\"Validate a Finnish Social Security Number.\n\n    This validator is based on [django-localflavor-fi][1].\n\n    [1]: https://github.com/django/django-localflavor-fi/\n\n    Examples:\n        >>> fi_ssn('010101-0101')\n        # Output: True\n        >>> fi_ssn('101010-0102')\n        # Output: ValidationError(func=fi_ssn, args=...)\n\n    Args:\n        value:\n            Social Security Number to be validated.\n        allow_temporal_ssn:\n            Whether to accept temporal SSN numbers. Temporal SSN numbers are the\n            ones where the serial is in the range [900-999]. By default temporal\n            SSN numbers are valid.\n\n    Returns:\n        (Literal[True]):\n            If `value` is a valid finnish SSN.\n        (ValidationError):\n            If `value` is an invalid finnish SSN.\n\n    > *New in version 0.5.0*.\n    \"\"\"\n    if not value:\n        return False\n    ssn_check_marks = \"0123456789ABCDEFHJKLMNPRSTUVWXY\"\n    if not (result := re.match(_ssn_pattern(ssn_check_marks), value)):\n        return False\n    gd = result.groupdict()\n    checksum = int(gd[\"date\"] + gd[\"serial\"])\n    return (\n        int(gd[\"serial\"]) >= 2\n        and (allow_temporal_ssn or int(gd[\"serial\"]) <= 899)\n        and ssn_check_marks[checksum % len(ssn_check_marks)] == gd[\"checksum\"]\n    )\n
"},{"location":"references/i18n/#validators.i18n.fr_department","title":"validators.i18n.fr_department(value)","text":"

Validate a french department number.

Examples:

>>> fr_department(20)  # can be an integer\n# Output: True\n>>> fr_department(\"20\")\n# Output: True\n>>> fr_department(\"971\")  # Guadeloupe\n# Output: True\n>>> fr_department(\"00\")\n# Output: ValidationError(func=fr_department, args=...)\n>>> fr_department('2A')  # Corsica\n# Output: True\n>>> fr_department('2B')\n# Output: True\n>>> fr_department('2C')\n# Output: ValidationError(func=fr_department, args=...)\n

Parameters:

Name Type Description Default value Union[str, int]

French department number to validate.

required

Returns:

Type Description Literal[True]

If value is a valid french department number.

ValidationError

If value is an invalid french department number.

New in version 0.23.0.

Source code in src/validators/i18n/fr.py
@validator\ndef fr_department(value: typing.Union[str, int]):\n    \"\"\"Validate a french department number.\n\n    Examples:\n        >>> fr_department(20)  # can be an integer\n        # Output: True\n        >>> fr_department(\"20\")\n        # Output: True\n        >>> fr_department(\"971\")  # Guadeloupe\n        # Output: True\n        >>> fr_department(\"00\")\n        # Output: ValidationError(func=fr_department, args=...)\n        >>> fr_department('2A')  # Corsica\n        # Output: True\n        >>> fr_department('2B')\n        # Output: True\n        >>> fr_department('2C')\n        # Output: ValidationError(func=fr_department, args=...)\n\n    Args:\n        value:\n            French department number to validate.\n\n    Returns:\n        (Literal[True]):\n            If `value` is a valid french department number.\n        (ValidationError):\n            If `value` is an invalid french department number.\n\n    > *New in version 0.23.0*.\n    \"\"\"\n    if not value:\n        return False\n    if isinstance(value, str):\n        if value in (\"2A\", \"2B\"):  # Corsica\n            return True\n        try:\n            value = int(value)\n        except ValueError:\n            return False\n    return 1 <= value <= 19 or 21 <= value <= 95 or 971 <= value <= 976  # Overseas departments\n
"},{"location":"references/i18n/#validators.i18n.fr_ssn","title":"validators.i18n.fr_ssn(value)","text":"

Validate a french Social Security Number.

Each french citizen has a distinct Social Security Number. For more information see French Social Security Number (sadly unavailable in english).

Examples:

>>> fr_ssn('1 84 12 76 451 089 46')\n# Output: True\n>>> fr_ssn('1 84 12 76 451 089')  # control key is optional\n# Output: True\n>>> fr_ssn('3 84 12 76 451 089 46')  # wrong gender number\n# Output: ValidationError(func=fr_ssn, args=...)\n>>> fr_ssn('1 84 12 76 451 089 47')  # wrong control key\n# Output: ValidationError(func=fr_ssn, args=...)\n

Parameters:

Name Type Description Default value str

French Social Security Number string to validate.

required

Returns:

Type Description Literal[True]

If value is a valid french Social Security Number.

ValidationError

If value is an invalid french Social Security Number.

New in version 0.23.0.

Source code in src/validators/i18n/fr.py
@validator\ndef fr_ssn(value: str):\n    \"\"\"Validate a french Social Security Number.\n\n    Each french citizen has a distinct Social Security Number.\n    For more information see [French Social Security Number][1] (sadly unavailable in english).\n\n    [1]: https://fr.wikipedia.org/wiki/Num%C3%A9ro_de_s%C3%A9curit%C3%A9_sociale_en_France\n\n    Examples:\n        >>> fr_ssn('1 84 12 76 451 089 46')\n        # Output: True\n        >>> fr_ssn('1 84 12 76 451 089')  # control key is optional\n        # Output: True\n        >>> fr_ssn('3 84 12 76 451 089 46')  # wrong gender number\n        # Output: ValidationError(func=fr_ssn, args=...)\n        >>> fr_ssn('1 84 12 76 451 089 47')  # wrong control key\n        # Output: ValidationError(func=fr_ssn, args=...)\n\n    Args:\n        value:\n            French Social Security Number string to validate.\n\n    Returns:\n        (Literal[True]):\n            If `value` is a valid french Social Security Number.\n        (ValidationError):\n            If `value` is an invalid french Social Security Number.\n\n    > *New in version 0.23.0*.\n    \"\"\"\n    if not value:\n        return False\n    matched = re.match(_ssn_pattern(), value)\n    if not matched:\n        return False\n    groups = list(matched.groups())\n    control_key = groups[-1]\n    department = groups[3]\n    if department != \"99\" and not fr_department(department):\n        # 99 stands for foreign born people\n        return False\n    if control_key is None:\n        # no control key provided, no additional check needed\n        return True\n    if len(department) == len(groups[4]):\n        # if the department number is 3 digits long (overseas departments),\n        # the town number must be 2 digits long\n        # and vice versa\n        return False\n    if department in (\"2A\", \"2B\"):\n        # Corsica's department numbers are not in the same range as the others\n        # thus 2A and 2B are replaced by 19 and 18 respectively to compute the control key\n        groups[3] = \"19\" if department == \"2A\" else \"18\"\n    # the control key is valid if it is equal to 97 - (the first 13 digits modulo 97)\n    digits = int(\"\".join(groups[:-1]))\n    return int(control_key) == (97 - (digits % 97))\n
"},{"location":"references/iban/","title":"iban","text":""},{"location":"references/iban/#validators.iban.iban","title":"validators.iban.iban(value)","text":"

Return whether or not given value is a valid IBAN code.

Examples:

>>> iban('DE29100500001061045672')\n# Output: True\n>>> iban('123456')\n# Output: ValidationError(func=iban, ...)\n

Parameters:

Name Type Description Default value str

IBAN string to validate.

required

Returns:

Type Description Literal[True]

If value is a valid IBAN code.

ValidationError

If value is an invalid IBAN code.

New in version 0.8.0

Source code in src/validators/iban.py
@validator\ndef iban(value: str, /):\n    \"\"\"Return whether or not given value is a valid IBAN code.\n\n    Examples:\n        >>> iban('DE29100500001061045672')\n        # Output: True\n        >>> iban('123456')\n        # Output: ValidationError(func=iban, ...)\n\n    Args:\n        value:\n            IBAN string to validate.\n\n    Returns:\n        (Literal[True]):\n            If `value` is a valid IBAN code.\n        (ValidationError):\n            If `value` is an invalid IBAN code.\n\n    > *New in version 0.8.0*\n    \"\"\"\n    return (\n        (re.match(r\"^[A-Z]{2}[0-9]{2}[A-Z0-9]{11,30}$\", value) and _mod_check(value))\n        if value\n        else False\n    )\n
"},{"location":"references/ip_address/","title":"ip_address","text":""},{"location":"references/ip_address/#validators.ip_address.ipv4","title":"validators.ip_address.ipv4(value, /, *, cidr=True, strict=False, host_bit=True)","text":"

Returns whether a given value is a valid IPv4 address.

From Python version 3.9.5 leading zeros are no longer tolerated and are treated as an error. The initial version of ipv4 validator was inspired from WTForms IPAddress validator.

Examples:

>>> ipv4('123.0.0.7')\n# Output: True\n>>> ipv4('1.1.1.1/8')\n# Output: True\n>>> ipv4('900.80.70.11')\n# Output: ValidationError(func=ipv4, args={'value': '900.80.70.11'})\n

Parameters:

Name Type Description Default value str

IP address string to validate.

required cidr bool

IP address string may contain CIDR notation

True strict bool

IP address string is strictly in CIDR notation

False host_bit bool

If False and host bits (along with network bits) are set in the supplied address, this function raises a validation error. ref IPv4Network.

True

Returns:

Type Description Literal[True]

If value is a valid IPv4 address.

ValidationError

If value is an invalid IPv4 address.

Note
  • In version 0.14.0:
    • Add supports for CIDR notation

New in version 0.2.0

Source code in src/validators/ip_address.py
@validator\ndef ipv4(value: str, /, *, cidr: bool = True, strict: bool = False, host_bit: bool = True):\n    \"\"\"Returns whether a given value is a valid IPv4 address.\n\n    From Python version 3.9.5 leading zeros are no longer tolerated\n    and are treated as an error. The initial version of ipv4 validator\n    was inspired from [WTForms IPAddress validator][1].\n\n    [1]: https://github.com/wtforms/wtforms/blob/master/src/wtforms/validators.py\n\n    Examples:\n        >>> ipv4('123.0.0.7')\n        # Output: True\n        >>> ipv4('1.1.1.1/8')\n        # Output: True\n        >>> ipv4('900.80.70.11')\n        # Output: ValidationError(func=ipv4, args={'value': '900.80.70.11'})\n\n    Args:\n        value:\n            IP address string to validate.\n        cidr:\n            IP address string may contain CIDR notation\n        strict:\n            IP address string is strictly in CIDR notation\n        host_bit:\n            If `False` and host bits (along with network bits) _are_ set in the supplied\n            address, this function raises a validation error. ref [IPv4Network][2].\n            [2]: https://docs.python.org/3/library/ipaddress.html#ipaddress.IPv4Network\n\n    Returns:\n        (Literal[True]):\n            If `value` is a valid IPv4 address.\n        (ValidationError):\n            If `value` is an invalid IPv4 address.\n\n    Note:\n        - *In version 0.14.0*:\n            - Add supports for CIDR notation\n\n    > *New in version 0.2.0*\n    \"\"\"\n    if not value:\n        return False\n    try:\n        if cidr:\n            if strict and value.count(\"/\") != 1:\n                raise ValueError(\"IPv4 address was expected in CIDR notation\")\n            return IPv4Network(value, strict=not host_bit)\n        return IPv4Address(value)\n    except (ValueError, AddressValueError, NetmaskValueError):\n        return False\n
"},{"location":"references/ip_address/#validators.ip_address.ipv6","title":"validators.ip_address.ipv6(value, /, *, cidr=True, strict=False, host_bit=True)","text":"

Returns if a given value is a valid IPv6 address.

Including IPv4-mapped IPv6 addresses. The initial version of ipv6 validator was inspired from WTForms IPAddress validator.

Examples:

>>> ipv6('::ffff:192.0.2.128')\n# Output: True\n>>> ipv6('::1/128')\n# Output: True\n>>> ipv6('abc.0.0.1')\n# Output: ValidationError(func=ipv6, args={'value': 'abc.0.0.1'})\n

Parameters:

Name Type Description Default value str

IP address string to validate.

required cidr bool

IP address string may contain CIDR annotation

True strict bool

IP address string is strictly in CIDR notation

False host_bit bool

If False and host bits (along with network bits) are set in the supplied address, this function raises a validation error. ref IPv6Network.

True

Returns:

Type Description Literal[True]

If value is a valid IPv6 address.

ValidationError

If value is an invalid IPv6 address.

Note
  • In version 0.14.0:
    • Add supports for CIDR notation

New in version 0.2.0

Source code in src/validators/ip_address.py
@validator\ndef ipv6(value: str, /, *, cidr: bool = True, strict: bool = False, host_bit: bool = True):\n    \"\"\"Returns if a given value is a valid IPv6 address.\n\n    Including IPv4-mapped IPv6 addresses. The initial version of ipv6 validator\n    was inspired from [WTForms IPAddress validator][1].\n\n    [1]: https://github.com/wtforms/wtforms/blob/master/src/wtforms/validators.py\n\n    Examples:\n        >>> ipv6('::ffff:192.0.2.128')\n        # Output: True\n        >>> ipv6('::1/128')\n        # Output: True\n        >>> ipv6('abc.0.0.1')\n        # Output: ValidationError(func=ipv6, args={'value': 'abc.0.0.1'})\n\n    Args:\n        value:\n            IP address string to validate.\n        cidr:\n            IP address string may contain CIDR annotation\n        strict:\n            IP address string is strictly in CIDR notation\n        host_bit:\n            If `False` and host bits (along with network bits) _are_ set in the supplied\n            address, this function raises a validation error. ref [IPv6Network][2].\n            [2]: https://docs.python.org/3/library/ipaddress.html#ipaddress.IPv6Network\n\n    Returns:\n        (Literal[True]):\n            If `value` is a valid IPv6 address.\n        (ValidationError):\n            If `value` is an invalid IPv6 address.\n\n    Note:\n        - *In version 0.14.0*:\n            - Add supports for CIDR notation\n\n    > *New in version 0.2.0*\n    \"\"\"\n    if not value:\n        return False\n    try:\n        if cidr:\n            if strict and value.count(\"/\") != 1:\n                raise ValueError(\"IPv6 address was expected in CIDR notation\")\n            return IPv6Network(value, strict=not host_bit)\n        return IPv6Address(value)\n    except (ValueError, AddressValueError, NetmaskValueError):\n        return False\n
"},{"location":"references/length/","title":"length","text":""},{"location":"references/length/#validators.length.length","title":"validators.length.length(value, /, *, min_val=0, max_val=0)","text":"

Return whether or not the length of given string is within a specified range.

Examples:

>>> length('something', min_val=2)\n# Output: True\n>>> length('something', min_val=9, max_val=9)\n# Output: True\n>>> length('something', max_val=5)\n# Output: ValidationError(func=length, ...)\n

Parameters:

Name Type Description Default value str

The string to validate.

required min_val int

The minimum required length of the string. If not provided, minimum length will not be checked.

0 max_val int

The maximum length of the string. If not provided, maximum length will not be checked.

0

Returns:

Type Description Literal[True]

If len(value) is in between the given conditions.

ValidationError

If len(value) is not in between the given conditions.

New in version 0.2.0.

Source code in src/validators/length.py
@validator\ndef length(value: str, /, *, min_val: int = 0, max_val: int = 0):\n    \"\"\"Return whether or not the length of given string is within a specified range.\n\n    Examples:\n        >>> length('something', min_val=2)\n        # Output: True\n        >>> length('something', min_val=9, max_val=9)\n        # Output: True\n        >>> length('something', max_val=5)\n        # Output: ValidationError(func=length, ...)\n\n    Args:\n        value:\n            The string to validate.\n        min_val:\n            The minimum required length of the string. If not provided,\n            minimum length will not be checked.\n        max_val:\n            The maximum length of the string. If not provided,\n            maximum length will not be checked.\n\n    Returns:\n        (Literal[True]):\n            If `len(value)` is in between the given conditions.\n        (ValidationError):\n            If `len(value)` is not in between the given conditions.\n\n    > *New in version 0.2.0*.\n    \"\"\"\n    return between(len(value), min_val=min_val, max_val=max_val) if value else False\n
"},{"location":"references/mac_address/","title":"mac_address","text":""},{"location":"references/mac_address/#validators.mac_address.mac_address","title":"validators.mac_address.mac_address(value)","text":"

Return whether or not given value is a valid MAC address.

This validator is based on WTForms MacAddress validator.

Examples:

>>> mac_address('01:23:45:67:ab:CD')\n# Output: True\n>>> mac_address('00:00:00:00:00')\n# Output: ValidationError(func=mac_address, args={'value': '00:00:00:00:00'})\n

Parameters:

Name Type Description Default value str

MAC address string to validate.

required

Returns:

Type Description Literal[True]

If value is a valid MAC address.

ValidationError

If value is an invalid MAC address.

New in version 0.2.0.

Source code in src/validators/mac_address.py
@validator\ndef mac_address(value: str, /):\n    \"\"\"Return whether or not given value is a valid MAC address.\n\n    This validator is based on [WTForms MacAddress validator][1].\n\n    [1]: https://github.com/wtforms/wtforms/blob/master/src/wtforms/validators.py#L482\n\n    Examples:\n        >>> mac_address('01:23:45:67:ab:CD')\n        # Output: True\n        >>> mac_address('00:00:00:00:00')\n        # Output: ValidationError(func=mac_address, args={'value': '00:00:00:00:00'})\n\n    Args:\n        value:\n            MAC address string to validate.\n\n    Returns:\n        (Literal[True]):\n            If `value` is a valid MAC address.\n        (ValidationError):\n            If `value` is an invalid MAC address.\n\n    > *New in version 0.2.0*.\n    \"\"\"\n    return re.match(r\"^([0-9A-Fa-f]{2}[:-]){5}([0-9A-Fa-f]{2})$\", value) if value else False\n
"},{"location":"references/slug/","title":"slug","text":""},{"location":"references/slug/#validators.slug.slug","title":"validators.slug.slug(value)","text":"

Validate whether or not given value is valid slug.

Valid slug can contain only lowercase alphanumeric characters and hyphens. It starts and ends with these lowercase alphanumeric characters.

Examples:

>>> slug('my-slug-2134')\n# Output: True\n>>> slug('my.slug')\n# Output: ValidationError(func=slug, args={'value': 'my.slug'})\n

Parameters:

Name Type Description Default value str

Slug string to validate.

required

Returns:

Type Description Literal[True]

If value is a valid slug.

ValidationError

If value is an invalid slug.

New in version 0.6.0.

Source code in src/validators/slug.py
@validator\ndef slug(value: str, /):\n    \"\"\"Validate whether or not given value is valid slug.\n\n    Valid slug can contain only lowercase alphanumeric characters and hyphens.\n    It starts and ends with these lowercase alphanumeric characters.\n\n    Examples:\n        >>> slug('my-slug-2134')\n        # Output: True\n        >>> slug('my.slug')\n        # Output: ValidationError(func=slug, args={'value': 'my.slug'})\n\n    Args:\n        value:\n            Slug string to validate.\n\n    Returns:\n        (Literal[True]):\n            If `value` is a valid slug.\n        (ValidationError):\n            If `value` is an invalid slug.\n\n    > *New in version 0.6.0*.\n    \"\"\"\n    return re.match(r\"^[a-z0-9]+(?:-[a-z0-9]+)*$\", value) if value else False\n
"},{"location":"references/url/","title":"url","text":""},{"location":"references/url/#validators.url.url","title":"validators.url.url(value, /, *, skip_ipv6_addr=False, skip_ipv4_addr=False, may_have_port=True, simple_host=False, strict_query=True, rfc_1034=False, rfc_2782=False)","text":"

Return whether or not given value is a valid URL.

This validator was inspired from URL validator of dperini. The following diagram is from urlly.

    foo://admin:hunter1@example.com:8042/over/there?name=ferret#nose\n    \\_/   \\___/ \\_____/ \\_________/ \\__/\\_________/ \\_________/ \\__/\n     |      |       |       |        |       |          |         |\n  scheme username password hostname port    path      query    fragment\n

Examples:

>>> url('http://duck.com')\n# Output: True\n>>> url('ftp://foobar.dk')\n# Output: True\n>>> url('http://10.0.0.1')\n# Output: True\n>>> url('http://example.com/\">user@example.com')\n# Output: ValidationError(func=url, ...)\n

Parameters:

Name Type Description Default value str

URL string to validate.

required skip_ipv6_addr bool

When URL string cannot contain an IPv6 address.

False skip_ipv4_addr bool

When URL string cannot contain an IPv4 address.

False may_have_port bool

URL string may contain port number.

True simple_host bool

URL string maybe only hyphens and alpha-numerals.

False strict_query bool

Fail validation on query string parsing error.

True rfc_1034 bool

Allow trailing dot in domain/host name. Ref: RFC 1034.

False rfc_2782 bool

Domain/Host name is of type service record. Ref: RFC 2782.

False

Returns:

Type Description Literal[True]

If value is a valid slug.

ValidationError

If value is an invalid slug.

Note
  • In version 0.11.3:
    • Added support for URLs containing localhost.
  • In version 0.11.0:
    • Made the regular expression case insensitive.
  • In version 0.10.3:
    • Added a public parameter.
  • In version 0.10.2:
    • Added support for various exotic URLs.
    • Fixed various false positives.

New in version 0.2.0.

Source code in src/validators/url.py
@validator\ndef url(\n    value: str,\n    /,\n    *,\n    skip_ipv6_addr: bool = False,\n    skip_ipv4_addr: bool = False,\n    may_have_port: bool = True,\n    simple_host: bool = False,\n    strict_query: bool = True,\n    rfc_1034: bool = False,\n    rfc_2782: bool = False,\n):\n    r\"\"\"Return whether or not given value is a valid URL.\n\n    This validator was inspired from [URL validator of dperini][1].\n    The following diagram is from [urlly][2].\n\n            foo://admin:hunter1@example.com:8042/over/there?name=ferret#nose\n            \\_/   \\___/ \\_____/ \\_________/ \\__/\\_________/ \\_________/ \\__/\n             |      |       |       |        |       |          |         |\n          scheme username password hostname port    path      query    fragment\n\n    [1]: https://gist.github.com/dperini/729294\n    [2]: https://github.com/treeform/urlly\n\n    Examples:\n        >>> url('http://duck.com')\n        # Output: True\n        >>> url('ftp://foobar.dk')\n        # Output: True\n        >>> url('http://10.0.0.1')\n        # Output: True\n        >>> url('http://example.com/\">user@example.com')\n        # Output: ValidationError(func=url, ...)\n\n    Args:\n        value:\n            URL string to validate.\n        skip_ipv6_addr:\n            When URL string cannot contain an IPv6 address.\n        skip_ipv4_addr:\n            When URL string cannot contain an IPv4 address.\n        may_have_port:\n            URL string may contain port number.\n        simple_host:\n            URL string maybe only hyphens and alpha-numerals.\n        strict_query:\n            Fail validation on query string parsing error.\n        rfc_1034:\n            Allow trailing dot in domain/host name.\n            Ref: [RFC 1034](https://www.rfc-editor.org/rfc/rfc1034).\n        rfc_2782:\n            Domain/Host name is of type service record.\n            Ref: [RFC 2782](https://www.rfc-editor.org/rfc/rfc2782).\n\n    Returns:\n        (Literal[True]):\n            If `value` is a valid slug.\n        (ValidationError):\n            If `value` is an invalid slug.\n\n    Note:\n        - *In version 0.11.3*:\n            - Added support for URLs containing localhost.\n        - *In version 0.11.0*:\n            - Made the regular expression case insensitive.\n        - *In version 0.10.3*:\n            - Added a `public` parameter.\n        - *In version 0.10.2*:\n            - Added support for various exotic URLs.\n            - Fixed various false positives.\n\n    > *New in version 0.2.0*.\n    \"\"\"\n    if not value or re.search(r\"\\s\", value):\n        # url must not contain any white\n        # spaces, they must be encoded\n        return False\n\n    try:\n        scheme, netloc, path, query, fragment = urlsplit(value)\n    except ValueError:\n        return False\n\n    return (\n        _validate_scheme(scheme)\n        and _validate_netloc(\n            netloc,\n            skip_ipv6_addr,\n            skip_ipv4_addr,\n            may_have_port,\n            simple_host,\n            rfc_1034,\n            rfc_2782,\n        )\n        and _validate_optionals(path, query, fragment, strict_query)\n    )\n
"},{"location":"references/utils/","title":"utils","text":""},{"location":"references/utils/#validators.utils.ValidationError","title":"validators.utils.ValidationError","text":"

Bases: Exception

Exception class when validation failure occurs.

Source code in src/validators/utils.py
class ValidationError(Exception):\n    \"\"\"Exception class when validation failure occurs.\"\"\"\n\n    def __init__(self, function: Callable[..., Any], arg_dict: Dict[str, Any], message: str = \"\"):\n        \"\"\"Initialize Validation Failure.\"\"\"\n        if message:\n            self.reason = message\n        self.func = function\n        self.__dict__.update(arg_dict)\n\n    def __repr__(self):\n        \"\"\"Repr Validation Failure.\"\"\"\n        return (\n            f\"ValidationError(func={self.func.__name__}, \"\n            + f\"args={({k: v for (k, v) in self.__dict__.items() if k != 'func'})})\"\n        )\n\n    def __str__(self):\n        \"\"\"Str Validation Failure.\"\"\"\n        return repr(self)\n\n    def __bool__(self):\n        \"\"\"Bool Validation Failure.\"\"\"\n        return False\n
"},{"location":"references/utils/#validators.utils.ValidationError.__bool__","title":"__bool__()","text":"

Bool Validation Failure.

Source code in src/validators/utils.py
def __bool__(self):\n    \"\"\"Bool Validation Failure.\"\"\"\n    return False\n
"},{"location":"references/utils/#validators.utils.ValidationError.__init__","title":"__init__(function, arg_dict, message='')","text":"

Initialize Validation Failure.

Source code in src/validators/utils.py
def __init__(self, function: Callable[..., Any], arg_dict: Dict[str, Any], message: str = \"\"):\n    \"\"\"Initialize Validation Failure.\"\"\"\n    if message:\n        self.reason = message\n    self.func = function\n    self.__dict__.update(arg_dict)\n
"},{"location":"references/utils/#validators.utils.ValidationError.__repr__","title":"__repr__()","text":"

Repr Validation Failure.

Source code in src/validators/utils.py
def __repr__(self):\n    \"\"\"Repr Validation Failure.\"\"\"\n    return (\n        f\"ValidationError(func={self.func.__name__}, \"\n        + f\"args={({k: v for (k, v) in self.__dict__.items() if k != 'func'})})\"\n    )\n
"},{"location":"references/utils/#validators.utils.ValidationError.__str__","title":"__str__()","text":"

Str Validation Failure.

Source code in src/validators/utils.py
def __str__(self):\n    \"\"\"Str Validation Failure.\"\"\"\n    return repr(self)\n
"},{"location":"references/utils/#validators.utils.validator","title":"validators.utils.validator(func)","text":"

A decorator that makes given function validator.

Whenever the given func returns False this decorator returns ValidationError object.

Examples:

>>> @validator\n... def even(value):\n...     return not (value % 2)\n>>> even(4)\n# Output: True\n>>> even(5)\n# Output: ValidationError(func=even, args={'value': 5})\n

Parameters:

Name Type Description Default func Callable[..., Any]

Function which is to be decorated.

required

Returns:

Type Description Callable[..., ValidationError | Literal[True]]

A decorator which returns either ValidationError or Literal[True].

New in version 2013.10.21.

Source code in src/validators/utils.py
def validator(func: Callable[..., Any]):\n    \"\"\"A decorator that makes given function validator.\n\n    Whenever the given `func` returns `False` this\n    decorator returns `ValidationError` object.\n\n    Examples:\n        >>> @validator\n        ... def even(value):\n        ...     return not (value % 2)\n        >>> even(4)\n        # Output: True\n        >>> even(5)\n        # Output: ValidationError(func=even, args={'value': 5})\n\n    Args:\n        func:\n            Function which is to be decorated.\n\n    Returns:\n        (Callable[..., ValidationError | Literal[True]]):\n            A decorator which returns either `ValidationError`\n            or `Literal[True]`.\n\n    > *New in version 2013.10.21*.\n    \"\"\"\n\n    @wraps(func)\n    def wrapper(*args: Any, **kwargs: Any):\n        try:\n            return (\n                True\n                if func(*args, **kwargs)\n                else ValidationError(func, _func_args_as_dict(func, *args, **kwargs))\n            )\n        except Exception as exp:\n            return ValidationError(func, _func_args_as_dict(func, *args, **kwargs), str(exp))\n\n    return wrapper\n
"},{"location":"references/uuid/","title":"uuid","text":""},{"location":"references/uuid/#validators.uuid.uuid","title":"validators.uuid.uuid(value)","text":"

Return whether or not given value is a valid UUID-v4 string.

This validator is based on WTForms UUID validator.

Examples:

>>> uuid('2bc1c94f-0deb-43e9-92a1-4775189ec9f8')\n# Output: True\n>>> uuid('2bc1c94f 0deb-43e9-92a1-4775189ec9f8')\n# Output: ValidationError(func=uuid, ...)\n

Parameters:

Name Type Description Default value Union[str, UUID]

UUID string or object to validate.

required

Returns:

Type Description Literal[True]

If value is a valid UUID.

ValidationError

If value is an invalid UUID.

New in version 0.2.0.

Source code in src/validators/uuid.py
@validator\ndef uuid(value: Union[str, UUID], /):\n    \"\"\"Return whether or not given value is a valid UUID-v4 string.\n\n    This validator is based on [WTForms UUID validator][1].\n\n    [1]: https://github.com/wtforms/wtforms/blob/master/src/wtforms/validators.py#L539\n\n    Examples:\n        >>> uuid('2bc1c94f-0deb-43e9-92a1-4775189ec9f8')\n        # Output: True\n        >>> uuid('2bc1c94f 0deb-43e9-92a1-4775189ec9f8')\n        # Output: ValidationError(func=uuid, ...)\n\n    Args:\n        value:\n            UUID string or object to validate.\n\n    Returns:\n        (Literal[True]):\n            If `value` is a valid UUID.\n        (ValidationError):\n            If `value` is an invalid UUID.\n\n    > *New in version 0.2.0*.\n    \"\"\"\n    if not value:\n        return False\n    if isinstance(value, UUID):\n        return True\n    try:\n        return UUID(value) or re.match(\n            r\"^[0-9a-fA-F]{8}-([0-9a-fA-F]{4}-){3}[0-9a-fA-F]{12}$\", value\n        )\n    except ValueError:\n        return False\n
"}]} \ No newline at end of file +{"config":{"lang":["en"],"separator":"[\\s\\-]+","pipeline":["stopWordFilter"]},"docs":[{"location":"","title":"validators - Python Data Validation for Humans\u2122","text":"

Python has all kinds of data validation tools, but every one of them seems to require defining a schema or form. I wanted to create a simple validation library where validating a simple value does not require defining a form or a schema.

>>> import validators\n>>> \n>>> validators.email('someone@example.com')\nTrue\n
"},{"location":"#resources","title":"Resources","text":"
  • Documentation
  • Bugtracker
  • Security
  • Code
"},{"location":"references/between/","title":"between","text":""},{"location":"references/between/#validators.between.between","title":"validators.between.between(value, /, *, min_val=None, max_val=None)","text":"

Validate that a number is between minimum and/or maximum value.

This will work with any comparable type, such as floats, decimals and dates not just integers. This validator is originally based on WTForms-NumberRange-Validator.

Examples:

>>> from datetime import datetime\n>>> between(5, min_val=2)\n# Output: True\n>>> between(13.2, min_val=13, max_val=14)\n# Output: True\n>>> between(500, max_val=400)\n# Output: ValidationError(func=between, args=...)\n>>> between(\n...     datetime(2000, 11, 11),\n...     min_val=datetime(1999, 11, 11)\n... )\n# Output: True\n

Parameters:

Name Type Description Default value PossibleValueTypes

Value which is to be compared.

required min_val Union[PossibleValueTypes, AbsMin, None]

The minimum required value of the number. If not provided, minimum value will not be checked.

None max_val Union[PossibleValueTypes, AbsMax, None]

The maximum value of the number. If not provided, maximum value will not be checked.

None

Returns:

Type Description Literal[True]

If value is in between the given conditions.

ValidationError

If value is not in between the given conditions.

Raises:

Type Description ValueError

If min_val is greater than max_val.

TypeError

If there's a type mismatch during comparison.

Note
  • PossibleValueTypes = TypeVar(\"PossibleValueTypes\", int, float, str, datetime)
  • If neither min_val nor max_val is provided, result will always be True.
Source code in src/validators/between.py
@validator\ndef between(\n    value: PossibleValueTypes,\n    /,\n    *,\n    min_val: Union[PossibleValueTypes, AbsMin, None] = None,\n    max_val: Union[PossibleValueTypes, AbsMax, None] = None,\n):\n    \"\"\"Validate that a number is between minimum and/or maximum value.\n\n    This will work with any comparable type, such as floats, decimals and dates\n    not just integers. This validator is originally based on [WTForms-NumberRange-Validator][1].\n\n    [1]: https://github.com/wtforms/wtforms/blob/master/src/wtforms/validators.py#L166-L220\n\n    Examples:\n        >>> from datetime import datetime\n        >>> between(5, min_val=2)\n        # Output: True\n        >>> between(13.2, min_val=13, max_val=14)\n        # Output: True\n        >>> between(500, max_val=400)\n        # Output: ValidationError(func=between, args=...)\n        >>> between(\n        ...     datetime(2000, 11, 11),\n        ...     min_val=datetime(1999, 11, 11)\n        ... )\n        # Output: True\n\n    Args:\n        value:\n            Value which is to be compared.\n        min_val:\n            The minimum required value of the number.\n            If not provided, minimum value will not be checked.\n        max_val:\n            The maximum value of the number.\n            If not provided, maximum value will not be checked.\n\n    Returns:\n        (Literal[True]):\n            If `value` is in between the given conditions.\n        (ValidationError):\n            If `value` is not in between the given conditions.\n\n    Raises:\n        (ValueError): If `min_val` is greater than `max_val`.\n        (TypeError): If there's a type mismatch during comparison.\n\n    Note:\n        - `PossibleValueTypes` = `TypeVar(\"PossibleValueTypes\", int, float, str, datetime)`\n        - If neither `min_val` nor `max_val` is provided, result will always be `True`.\n    \"\"\"\n    if value is None:\n        return False\n\n    if max_val is None:\n        max_val = AbsMax()\n    if min_val is None:\n        min_val = AbsMin()\n\n    try:\n        if min_val > max_val:\n            raise ValueError(\"`min_val` cannot be greater than `max_val`\")\n    except TypeError as err:\n        raise TypeError(\"Comparison type mismatch\") from err\n\n    return min_val <= value <= max_val\n
"},{"location":"references/btc_address/","title":"btc_address","text":""},{"location":"references/btc_address/#validators.btc_address.btc_address","title":"validators.btc_address.btc_address(value)","text":"

Return whether or not given value is a valid bitcoin address.

Full validation is implemented for P2PKH and P2SH addresses. For segwit addresses a regexp is used to provide a reasonable estimate on whether the address is valid.

Examples:

>>> btc_address('3Cwgr2g7vsi1bXDUkpEnVoRLA9w4FZfC69')\n# Output: True\n>>> btc_address('1BvBMsEYstWetqTFn5Au4m4GFg7xJaNVN2')\n# Output: ValidationError(func=btc_address, args=...)\n

Parameters:

Name Type Description Default value str

Bitcoin address string to validate.

required

Returns:

Type Description Literal[True]

If value is a valid bitcoin address.

ValidationError

If value is an invalid bitcoin address.

New in version 0.18.0.

Source code in src/validators/btc_address.py
@validator\ndef btc_address(value: str, /):\n    \"\"\"Return whether or not given value is a valid bitcoin address.\n\n    Full validation is implemented for P2PKH and P2SH addresses.\n    For segwit addresses a regexp is used to provide a reasonable\n    estimate on whether the address is valid.\n\n    Examples:\n        >>> btc_address('3Cwgr2g7vsi1bXDUkpEnVoRLA9w4FZfC69')\n        # Output: True\n        >>> btc_address('1BvBMsEYstWetqTFn5Au4m4GFg7xJaNVN2')\n        # Output: ValidationError(func=btc_address, args=...)\n\n    Args:\n        value:\n            Bitcoin address string to validate.\n\n    Returns:\n        (Literal[True]):\n            If `value` is a valid bitcoin address.\n        (ValidationError):\n            If `value` is an invalid bitcoin address.\n\n    > *New in version 0.18.0*.\n    \"\"\"\n    if not value:\n        return False\n\n    return (\n        # segwit pattern\n        re.compile(r\"^(bc|tc)[0-3][02-9ac-hj-np-z]{14,74}$\").match(value)\n        if value[:2] in (\"bc\", \"tb\")\n        else _validate_old_btc_address(value)\n    )\n
"},{"location":"references/card/","title":"card","text":""},{"location":"references/card/#validators.card.amex","title":"validators.card.amex(value)","text":"

Return whether or not given value is a valid American Express card number.

Examples:

>>> amex('378282246310005')\n# Output: True\n>>> amex('4242424242424242')\n# Output: ValidationError(func=amex, args={'value': '4242424242424242'})\n

Parameters:

Name Type Description Default value str

American Express card number string to validate

required

Returns:

Type Description Literal[True]

If value is a valid American Express card number.

ValidationError

If value is an invalid American Express card number.

New in version 0.15.0.

Source code in src/validators/card.py
@validator\ndef amex(value: str, /):\n    \"\"\"Return whether or not given value is a valid American Express card number.\n\n    Examples:\n        >>> amex('378282246310005')\n        # Output: True\n        >>> amex('4242424242424242')\n        # Output: ValidationError(func=amex, args={'value': '4242424242424242'})\n\n    Args:\n        value:\n            American Express card number string to validate\n\n    Returns:\n        (Literal[True]):\n            If `value` is a valid American Express card number.\n        (ValidationError):\n            If `value` is an invalid American Express card number.\n\n    > *New in version 0.15.0*.\n    \"\"\"\n    pattern = re.compile(r\"^(34|37)\")\n    return card_number(value) and len(value) == 15 and pattern.match(value)\n
"},{"location":"references/card/#validators.card.card_number","title":"validators.card.card_number(value)","text":"

Return whether or not given value is a valid generic card number.

This validator is based on Luhn's algorithm.

Examples:

>>> card_number('4242424242424242')\n# Output: True\n>>> card_number('4242424242424241')\n# Output: ValidationError(func=card_number, args={'value': '4242424242424241'})\n

Parameters:

Name Type Description Default value str

Generic card number string to validate

required

Returns:

Type Description Literal[True]

If value is a valid generic card number.

ValidationError

If value is an invalid generic card number.

New in version 0.15.0.

Source code in src/validators/card.py
@validator\ndef card_number(value: str, /):\n    \"\"\"Return whether or not given value is a valid generic card number.\n\n    This validator is based on [Luhn's algorithm][1].\n\n    [1]: https://github.com/mmcloughlin/luhn\n\n    Examples:\n        >>> card_number('4242424242424242')\n        # Output: True\n        >>> card_number('4242424242424241')\n        # Output: ValidationError(func=card_number, args={'value': '4242424242424241'})\n\n    Args:\n        value:\n            Generic card number string to validate\n\n    Returns:\n        (Literal[True]):\n            If `value` is a valid generic card number.\n        (ValidationError):\n            If `value` is an invalid generic card number.\n\n    > *New in version 0.15.0*.\n    \"\"\"\n    if not value:\n        return False\n    try:\n        digits = list(map(int, value))\n        odd_sum = sum(digits[-1::-2])\n        even_sum = sum(sum(divmod(2 * d, 10)) for d in digits[-2::-2])\n        return (odd_sum + even_sum) % 10 == 0\n    except ValueError:\n        return False\n
"},{"location":"references/card/#validators.card.diners","title":"validators.card.diners(value)","text":"

Return whether or not given value is a valid Diners Club card number.

Examples:

>>> diners('3056930009020004')\n# Output: True\n>>> diners('4242424242424242')\n# Output: ValidationError(func=diners, args={'value': '4242424242424242'})\n

Parameters:

Name Type Description Default value str

Diners Club card number string to validate

required

Returns:

Type Description Literal[True]

If value is a valid Diners Club card number.

ValidationError

If value is an invalid Diners Club card number.

New in version 0.15.0.

Source code in src/validators/card.py
@validator\ndef diners(value: str, /):\n    \"\"\"Return whether or not given value is a valid Diners Club card number.\n\n    Examples:\n        >>> diners('3056930009020004')\n        # Output: True\n        >>> diners('4242424242424242')\n        # Output: ValidationError(func=diners, args={'value': '4242424242424242'})\n\n    Args:\n        value:\n            Diners Club card number string to validate\n\n    Returns:\n        (Literal[True]):\n            If `value` is a valid Diners Club card number.\n        (ValidationError):\n            If `value` is an invalid Diners Club card number.\n\n    > *New in version 0.15.0*.\n    \"\"\"\n    pattern = re.compile(r\"^(30|36|38|39)\")\n    return card_number(value) and len(value) in {14, 16} and pattern.match(value)\n
"},{"location":"references/card/#validators.card.discover","title":"validators.card.discover(value)","text":"

Return whether or not given value is a valid Discover card number.

Examples:

>>> discover('6011111111111117')\n# Output: True\n>>> discover('4242424242424242')\n# Output: ValidationError(func=discover, args={'value': '4242424242424242'})\n

Parameters:

Name Type Description Default value str

Discover card number string to validate

required

Returns:

Type Description Literal[True]

If value is a valid Discover card number.

ValidationError

If value is an invalid Discover card number.

New in version 0.15.0.

Source code in src/validators/card.py
@validator\ndef discover(value: str, /):\n    \"\"\"Return whether or not given value is a valid Discover card number.\n\n    Examples:\n        >>> discover('6011111111111117')\n        # Output: True\n        >>> discover('4242424242424242')\n        # Output: ValidationError(func=discover, args={'value': '4242424242424242'})\n\n    Args:\n        value:\n            Discover card number string to validate\n\n    Returns:\n        (Literal[True]):\n            If `value` is a valid Discover card number.\n        (ValidationError):\n            If `value` is an invalid Discover card number.\n\n    > *New in version 0.15.0*.\n    \"\"\"\n    pattern = re.compile(r\"^(60|64|65)\")\n    return card_number(value) and len(value) == 16 and pattern.match(value)\n
"},{"location":"references/card/#validators.card.jcb","title":"validators.card.jcb(value)","text":"

Return whether or not given value is a valid JCB card number.

Examples:

>>> jcb('3566002020360505')\n# Output: True\n>>> jcb('4242424242424242')\n# Output: ValidationError(func=jcb, args={'value': '4242424242424242'})\n

Parameters:

Name Type Description Default value str

JCB card number string to validate

required

Returns:

Type Description Literal[True]

If value is a valid JCB card number.

ValidationError

If value is an invalid JCB card number.

New in version 0.15.0.

Source code in src/validators/card.py
@validator\ndef jcb(value: str, /):\n    \"\"\"Return whether or not given value is a valid JCB card number.\n\n    Examples:\n        >>> jcb('3566002020360505')\n        # Output: True\n        >>> jcb('4242424242424242')\n        # Output: ValidationError(func=jcb, args={'value': '4242424242424242'})\n\n    Args:\n        value:\n            JCB card number string to validate\n\n    Returns:\n        (Literal[True]):\n            If `value` is a valid JCB card number.\n        (ValidationError):\n            If `value` is an invalid JCB card number.\n\n    > *New in version 0.15.0*.\n    \"\"\"\n    pattern = re.compile(r\"^35\")\n    return card_number(value) and len(value) == 16 and pattern.match(value)\n
"},{"location":"references/card/#validators.card.mastercard","title":"validators.card.mastercard(value)","text":"

Return whether or not given value is a valid Mastercard card number.

Examples:

>>> mastercard('5555555555554444')\n# Output: True\n>>> mastercard('4242424242424242')\n# Output: ValidationError(func=mastercard, args={'value': '4242424242424242'})\n

Parameters:

Name Type Description Default value str

Mastercard card number string to validate

required

Returns:

Type Description Literal[True]

If value is a valid Mastercard card number.

ValidationError

If value is an invalid Mastercard card number.

New in version 0.15.0.

Source code in src/validators/card.py
@validator\ndef mastercard(value: str, /):\n    \"\"\"Return whether or not given value is a valid Mastercard card number.\n\n    Examples:\n        >>> mastercard('5555555555554444')\n        # Output: True\n        >>> mastercard('4242424242424242')\n        # Output: ValidationError(func=mastercard, args={'value': '4242424242424242'})\n\n    Args:\n        value:\n            Mastercard card number string to validate\n\n    Returns:\n        (Literal[True]):\n            If `value` is a valid Mastercard card number.\n        (ValidationError):\n            If `value` is an invalid Mastercard card number.\n\n    > *New in version 0.15.0*.\n    \"\"\"\n    pattern = re.compile(r\"^(51|52|53|54|55|22|23|24|25|26|27)\")\n    return card_number(value) and len(value) == 16 and pattern.match(value)\n
"},{"location":"references/card/#validators.card.unionpay","title":"validators.card.unionpay(value)","text":"

Return whether or not given value is a valid UnionPay card number.

Examples:

>>> unionpay('6200000000000005')\n# Output: True\n>>> unionpay('4242424242424242')\n# Output: ValidationError(func=unionpay, args={'value': '4242424242424242'})\n

Parameters:

Name Type Description Default value str

UnionPay card number string to validate

required

Returns:

Type Description Literal[True]

If value is a valid UnionPay card number.

ValidationError

If value is an invalid UnionPay card number.

New in version 0.15.0.

Source code in src/validators/card.py
@validator\ndef unionpay(value: str, /):\n    \"\"\"Return whether or not given value is a valid UnionPay card number.\n\n    Examples:\n        >>> unionpay('6200000000000005')\n        # Output: True\n        >>> unionpay('4242424242424242')\n        # Output: ValidationError(func=unionpay, args={'value': '4242424242424242'})\n\n    Args:\n        value:\n            UnionPay card number string to validate\n\n    Returns:\n        (Literal[True]):\n            If `value` is a valid UnionPay card number.\n        (ValidationError):\n            If `value` is an invalid UnionPay card number.\n\n    > *New in version 0.15.0*.\n    \"\"\"\n    pattern = re.compile(r\"^62\")\n    return card_number(value) and len(value) == 16 and pattern.match(value)\n
"},{"location":"references/card/#validators.card.visa","title":"validators.card.visa(value)","text":"

Return whether or not given value is a valid Visa card number.

Examples:

>>> visa('4242424242424242')\n# Output: True\n>>> visa('2223003122003222')\n# Output: ValidationError(func=visa, args={'value': '2223003122003222'})\n

Parameters:

Name Type Description Default value str

Visa card number string to validate

required

Returns:

Type Description Literal[True]

If value is a valid Visa card number.

ValidationError

If value is an invalid Visa card number.

New in version 0.15.0.

Source code in src/validators/card.py
@validator\ndef visa(value: str, /):\n    \"\"\"Return whether or not given value is a valid Visa card number.\n\n    Examples:\n        >>> visa('4242424242424242')\n        # Output: True\n        >>> visa('2223003122003222')\n        # Output: ValidationError(func=visa, args={'value': '2223003122003222'})\n\n    Args:\n        value:\n            Visa card number string to validate\n\n    Returns:\n        (Literal[True]):\n            If `value` is a valid Visa card number.\n        (ValidationError):\n            If `value` is an invalid Visa card number.\n\n    > *New in version 0.15.0*.\n    \"\"\"\n    pattern = re.compile(r\"^4\")\n    return card_number(value) and len(value) == 16 and pattern.match(value)\n
"},{"location":"references/country_code/","title":"country_code","text":""},{"location":"references/country_code/#validators.country_code.country_code","title":"validators.country_code.country_code(value, /, *, iso_format='auto')","text":"

Validates given country code.

This performs a case-sensitive ISO 3166 country code validation.

Examples:

>>> country_code('GB', iso_format='alpha3')\n# Output: False\n>>> country_code('USA')\n# Output: True\n>>> country_code('840', iso_format='numeric')\n# Output: True\n>>> country_code('iN', iso_format='alpha2')\n# Output: False\n>>> country_code('ZWE', iso_format='alpha3')\n# Output: True\n

Parameters:

Name Type Description Default value str

Country code string to validate.

required iso_format str

ISO format to be used. Available options are: auto, alpha2, alpha3 and numeric.

'auto'

Returns:

Type Description Literal[True]

If value is a valid country code.

ValidationError

If value is an invalid country code.

Source code in src/validators/country_code.py
@validator\ndef country_code(value: str, /, *, iso_format: str = \"auto\"):\n    \"\"\"Validates given country code.\n\n    This performs a case-sensitive [ISO 3166][1] country code validation.\n\n    [1]: https://www.iso.org/iso-3166-country-codes.html\n\n    Examples:\n        >>> country_code('GB', iso_format='alpha3')\n        # Output: False\n        >>> country_code('USA')\n        # Output: True\n        >>> country_code('840', iso_format='numeric')\n        # Output: True\n        >>> country_code('iN', iso_format='alpha2')\n        # Output: False\n        >>> country_code('ZWE', iso_format='alpha3')\n        # Output: True\n\n    Args:\n        value:\n            Country code string to validate.\n        iso_format:\n            ISO format to be used. Available options are:\n            `auto`, `alpha2`, `alpha3` and `numeric`.\n\n    Returns:\n        (Literal[True]):\n            If `value` is a valid country code.\n        (ValidationError):\n            If `value` is an invalid country code.\n    \"\"\"\n    if not value:\n        return False\n\n    if not (1 < len(value) < 4):\n        return False\n\n    if iso_format == \"auto\" and (iso_format := get_code_type(value)) == \"invalid\":\n        return False\n\n    if iso_format == \"alpha2\":\n        return value in alpha_2\n    if iso_format == \"alpha3\":\n        return value in alpha_3\n    return value in numeric if iso_format == \"numeric\" else False\n
"},{"location":"references/domain/","title":"domain","text":""},{"location":"references/domain/#validators.domain.domain","title":"validators.domain.domain(value, /, *, rfc_1034=False, rfc_2782=False)","text":"

Return whether or not given value is a valid domain.

Examples:

>>> domain('example.com')\n# Output: True\n>>> domain('example.com/')\n# Output: ValidationError(func=domain, ...)\n>>> # Supports IDN domains as well::\n>>> domain('xn----gtbspbbmkef.xn--p1ai')\n# Output: True\n

Parameters:

Name Type Description Default value str

Domain string to validate.

required rfc_1034 bool

Allow trailing dot in domain name. Ref: RFC 1034.

False rfc_2782 bool

Domain name is of type service record. Ref: RFC 2782.

False

Returns:

Type Description Literal[True]

If value is a valid domain name.

ValidationError

If value is an invalid domain name.

Note
  • In version 0.10.0:
    • Added support for internationalized domain name (IDN) validation.

New in version 0.9.0.

Source code in src/validators/domain.py
@validator\ndef domain(value: str, /, *, rfc_1034: bool = False, rfc_2782: bool = False):\n    \"\"\"Return whether or not given value is a valid domain.\n\n    Examples:\n        >>> domain('example.com')\n        # Output: True\n        >>> domain('example.com/')\n        # Output: ValidationError(func=domain, ...)\n        >>> # Supports IDN domains as well::\n        >>> domain('xn----gtbspbbmkef.xn--p1ai')\n        # Output: True\n\n    Args:\n        value:\n            Domain string to validate.\n        rfc_1034:\n            Allow trailing dot in domain name.\n            Ref: [RFC 1034](https://www.rfc-editor.org/rfc/rfc1034).\n        rfc_2782:\n            Domain name is of type service record.\n            Ref: [RFC 2782](https://www.rfc-editor.org/rfc/rfc2782).\n\n\n    Returns:\n        (Literal[True]):\n            If `value` is a valid domain name.\n        (ValidationError):\n            If `value` is an invalid domain name.\n\n    Note:\n        - *In version 0.10.0*:\n            - Added support for internationalized domain name (IDN) validation.\n\n    > *New in version 0.9.0*.\n    \"\"\"\n    if not value:\n        return False\n    try:\n        return not re.search(r\"\\s\", value) and re.match(\n            # First character of the domain\n            rf\"^(?:[a-zA-Z0-9{'_'if rfc_2782 else ''}]\"\n            # Sub domain + hostname\n            + r\"(?:[a-zA-Z0-9-_]{0,61}[A-Za-z0-9])?\\.)\"\n            # First 61 characters of the gTLD\n            + r\"+[A-Za-z0-9][A-Za-z0-9-_]{0,61}\"\n            # Last character of the gTLD\n            + rf\"[A-Za-z]{r'.$' if rfc_1034 else r'$'}\",\n            value.encode(\"idna\").decode(\"utf-8\"),\n            re.IGNORECASE,\n        )\n    except UnicodeError:\n        return False\n
"},{"location":"references/email/","title":"email","text":""},{"location":"references/email/#validators.email.email","title":"validators.email.email(value, /, *, ipv6_address=False, ipv4_address=False, simple_host=False, rfc_1034=False, rfc_2782=False)","text":"

Validate an email address.

This was inspired from Django's email validator. Also ref: RFC 1034, RFC 5321 and RFC 5322.

Examples:

>>> email('someone@example.com')\n# Output: True\n>>> email('bogus@@')\n# Output: ValidationError(email=email, args={'value': 'bogus@@'})\n

Parameters:

Name Type Description Default value str

eMail string to validate.

required ipv6_address bool

When the domain part is an IPv6 address.

False ipv4_address bool

When the domain part is an IPv4 address.

False simple_host bool

When the domain part is a simple hostname.

False rfc_1034 bool

Allow trailing dot in domain name. Ref: RFC 1034.

False rfc_2782 bool

Domain name is of type service record. Ref: RFC 2782.

False

Returns:

Type Description Literal[True]

If value is a valid eMail.

ValidationError

If value is an invalid eMail.

New in version 0.1.0.

Source code in src/validators/email.py
@validator\ndef email(\n    value: str,\n    /,\n    *,\n    ipv6_address: bool = False,\n    ipv4_address: bool = False,\n    simple_host: bool = False,\n    rfc_1034: bool = False,\n    rfc_2782: bool = False,\n):\n    \"\"\"Validate an email address.\n\n    This was inspired from [Django's email validator][1].\n    Also ref: [RFC 1034][2], [RFC 5321][3] and [RFC 5322][4].\n\n    [1]: https://github.com/django/django/blob/main/django/core/validators.py#L174\n    [2]: https://www.rfc-editor.org/rfc/rfc1034\n    [3]: https://www.rfc-editor.org/rfc/rfc5321\n    [4]: https://www.rfc-editor.org/rfc/rfc5322\n\n    Examples:\n        >>> email('someone@example.com')\n        # Output: True\n        >>> email('bogus@@')\n        # Output: ValidationError(email=email, args={'value': 'bogus@@'})\n\n    Args:\n        value:\n            eMail string to validate.\n        ipv6_address:\n            When the domain part is an IPv6 address.\n        ipv4_address:\n            When the domain part is an IPv4 address.\n        simple_host:\n            When the domain part is a simple hostname.\n        rfc_1034:\n            Allow trailing dot in domain name.\n            Ref: [RFC 1034](https://www.rfc-editor.org/rfc/rfc1034).\n        rfc_2782:\n            Domain name is of type service record.\n            Ref: [RFC 2782](https://www.rfc-editor.org/rfc/rfc2782).\n\n    Returns:\n        (Literal[True]):\n            If `value` is a valid eMail.\n        (ValidationError):\n            If `value` is an invalid eMail.\n\n    > *New in version 0.1.0*.\n    \"\"\"\n    if not value or value.count(\"@\") != 1:\n        return False\n\n    username_part, domain_part = value.rsplit(\"@\", 1)\n\n    if len(username_part) > 64 or len(domain_part) > 253:\n        # ref: RFC 1034 and 5231\n        return False\n\n    if ipv6_address or ipv4_address:\n        if domain_part.startswith(\"[\") and domain_part.endswith(\"]\"):\n            # ref: RFC 5321\n            domain_part = domain_part.lstrip(\"[\").rstrip(\"]\")\n        else:\n            return False\n\n    return (\n        bool(\n            hostname(\n                domain_part,\n                skip_ipv6_addr=not ipv6_address,\n                skip_ipv4_addr=not ipv4_address,\n                may_have_port=False,\n                maybe_simple=simple_host,\n                rfc_1034=rfc_1034,\n                rfc_2782=rfc_2782,\n            )\n        )\n        if re.match(\n            # dot-atom\n            r\"(^[-!#$%&'*+/=?^_`{}|~0-9A-Z]+(\\.[-!#$%&'*+/=?^_`{}|~0-9A-Z]+)*$\"\n            # quoted-string\n            + r'|^\"([\\001-\\010\\013\\014\\016-\\037!#-\\[\\]-\\177]|\\\\[\\001-\\011\\013\\014\\016-\\177])*\"$)',\n            username_part,\n            re.IGNORECASE,\n        )\n        else False\n    )\n
"},{"location":"references/hashes/","title":"hashes","text":""},{"location":"references/hashes/#validators.hashes.md5","title":"validators.hashes.md5(value)","text":"

Return whether or not given value is a valid MD5 hash.

Examples:

>>> md5('d41d8cd98f00b204e9800998ecf8427e')\n# Output: True\n>>> md5('900zz11')\n# Output: ValidationError(func=md5, args={'value': '900zz11'})\n

Parameters:

Name Type Description Default value str

MD5 string to validate.

required

Returns:

Type Description Literal[True]

If value is a valid MD5 hash.

ValidationError

If value is an invalid MD5 hash.

New in version 0.12.1

Source code in src/validators/hashes.py
@validator\ndef md5(value: str, /):\n    \"\"\"Return whether or not given value is a valid MD5 hash.\n\n    Examples:\n        >>> md5('d41d8cd98f00b204e9800998ecf8427e')\n        # Output: True\n        >>> md5('900zz11')\n        # Output: ValidationError(func=md5, args={'value': '900zz11'})\n\n    Args:\n        value:\n            MD5 string to validate.\n\n    Returns:\n        (Literal[True]):\n            If `value` is a valid MD5 hash.\n        (ValidationError):\n            If `value` is an invalid MD5 hash.\n\n    > *New in version 0.12.1*\n    \"\"\"\n    return re.match(r\"^[0-9a-f]{32}$\", value, re.IGNORECASE) if value else False\n
"},{"location":"references/hashes/#validators.hashes.sha1","title":"validators.hashes.sha1(value)","text":"

Return whether or not given value is a valid SHA1 hash.

Examples:

>>> sha1('da39a3ee5e6b4b0d3255bfef95601890afd80709')\n# Output: True\n>>> sha1('900zz11')\n# Output: ValidationError(func=sha1, args={'value': '900zz11'})\n

Parameters:

Name Type Description Default value str

SHA1 string to validate.

required

Returns:

Type Description Literal[True]

If value is a valid SHA1 hash.

ValidationError

If value is an invalid SHA1 hash.

New in version 0.12.1

Source code in src/validators/hashes.py
@validator\ndef sha1(value: str, /):\n    \"\"\"Return whether or not given value is a valid SHA1 hash.\n\n    Examples:\n        >>> sha1('da39a3ee5e6b4b0d3255bfef95601890afd80709')\n        # Output: True\n        >>> sha1('900zz11')\n        # Output: ValidationError(func=sha1, args={'value': '900zz11'})\n\n    Args:\n        value:\n            SHA1 string to validate.\n\n    Returns:\n        (Literal[True]):\n            If `value` is a valid SHA1 hash.\n        (ValidationError):\n            If `value` is an invalid SHA1 hash.\n\n    > *New in version 0.12.1*\n    \"\"\"\n    return re.match(r\"^[0-9a-f]{40}$\", value, re.IGNORECASE) if value else False\n
"},{"location":"references/hashes/#validators.hashes.sha224","title":"validators.hashes.sha224(value)","text":"

Return whether or not given value is a valid SHA224 hash.

Examples:

>>> sha224('d14a028c2a3a2bc9476102bb288234c415a2b01f828ea62ac5b3e42f')\n# Output: True\n>>> sha224('900zz11')\n# Output: ValidationError(func=sha224, args={'value': '900zz11'})\n

Parameters:

Name Type Description Default value str

SHA224 string to validate.

required

Returns:

Type Description Literal[True]

If value is a valid SHA224 hash.

ValidationError

If value is an invalid SHA224 hash.

New in version 0.12.1

Source code in src/validators/hashes.py
@validator\ndef sha224(value: str, /):\n    \"\"\"Return whether or not given value is a valid SHA224 hash.\n\n    Examples:\n        >>> sha224('d14a028c2a3a2bc9476102bb288234c415a2b01f828ea62ac5b3e42f')\n        # Output: True\n        >>> sha224('900zz11')\n        # Output: ValidationError(func=sha224, args={'value': '900zz11'})\n\n    Args:\n        value:\n            SHA224 string to validate.\n\n    Returns:\n        (Literal[True]):\n            If `value` is a valid SHA224 hash.\n        (ValidationError):\n            If `value` is an invalid SHA224 hash.\n\n    > *New in version 0.12.1*\n    \"\"\"\n    return re.match(r\"^[0-9a-f]{56}$\", value, re.IGNORECASE) if value else False\n
"},{"location":"references/hashes/#validators.hashes.sha256","title":"validators.hashes.sha256(value)","text":"

Return whether or not given value is a valid SHA256 hash.

Examples:

>>> sha256(\n...     'e3b0c44298fc1c149afbf4c8996fb924'\n...     '27ae41e4649b934ca495991b7852b855'\n... )\n# Output: True\n>>> sha256('900zz11')\n# Output: ValidationError(func=sha256, args={'value': '900zz11'})\n

Parameters:

Name Type Description Default value str

SHA256 string to validate.

required

Returns:

Type Description Literal[True]

If value is a valid SHA256 hash.

ValidationError

If value is an invalid SHA256 hash.

New in version 0.12.1

Source code in src/validators/hashes.py
@validator\ndef sha256(value: str, /):\n    \"\"\"Return whether or not given value is a valid SHA256 hash.\n\n    Examples:\n        >>> sha256(\n        ...     'e3b0c44298fc1c149afbf4c8996fb924'\n        ...     '27ae41e4649b934ca495991b7852b855'\n        ... )\n        # Output: True\n        >>> sha256('900zz11')\n        # Output: ValidationError(func=sha256, args={'value': '900zz11'})\n\n    Args:\n        value:\n            SHA256 string to validate.\n\n    Returns:\n        (Literal[True]):\n            If `value` is a valid SHA256 hash.\n        (ValidationError):\n            If `value` is an invalid SHA256 hash.\n\n    > *New in version 0.12.1*\n    \"\"\"\n    return re.match(r\"^[0-9a-f]{64}$\", value, re.IGNORECASE) if value else False\n
"},{"location":"references/hashes/#validators.hashes.sha512","title":"validators.hashes.sha512(value)","text":"

Return whether or not given value is a valid SHA512 hash.

Examples:

>>> sha512(\n...     'cf83e1357eefb8bdf1542850d66d8007d620e4050b5715dc83f4a921d36ce'\n...     '9ce47d0d13c5d85f2b0ff8318d2877eec2f63b931bd47417a81a538327af9'\n...     '27da3e'\n... )\n# Output: True\n>>> sha512('900zz11')\n# Output: ValidationError(func=sha512, args={'value': '900zz11'})\n

Parameters:

Name Type Description Default value str

SHA512 string to validate.

required

Returns:

Type Description Literal[True]

If value is a valid SHA512 hash.

ValidationError

If value is an invalid SHA512 hash.

New in version 0.12.1

Source code in src/validators/hashes.py
@validator\ndef sha512(value: str, /):\n    \"\"\"Return whether or not given value is a valid SHA512 hash.\n\n    Examples:\n        >>> sha512(\n        ...     'cf83e1357eefb8bdf1542850d66d8007d620e4050b5715dc83f4a921d36ce'\n        ...     '9ce47d0d13c5d85f2b0ff8318d2877eec2f63b931bd47417a81a538327af9'\n        ...     '27da3e'\n        ... )\n        # Output: True\n        >>> sha512('900zz11')\n        # Output: ValidationError(func=sha512, args={'value': '900zz11'})\n\n    Args:\n        value:\n            SHA512 string to validate.\n\n    Returns:\n        (Literal[True]):\n            If `value` is a valid SHA512 hash.\n        (ValidationError):\n            If `value` is an invalid SHA512 hash.\n\n    > *New in version 0.12.1*\n    \"\"\"\n    return re.match(r\"^[0-9a-f]{128}$\", value, re.IGNORECASE) if value else False\n
"},{"location":"references/hostname/","title":"hostname","text":""},{"location":"references/hostname/#validators.hostname.hostname","title":"validators.hostname.hostname(value, /, *, skip_ipv6_addr=False, skip_ipv4_addr=False, may_have_port=True, maybe_simple=True, rfc_1034=False, rfc_2782=False)","text":"

Return whether or not given value is a valid hostname.

Examples:

>>> hostname(\"ubuntu-pc:443\")\n# Output: True\n>>> hostname(\"this-pc\")\n# Output: True\n>>> hostname(\"xn----gtbspbbmkef.xn--p1ai:65535\")\n# Output: True\n>>> hostname(\"_example.com\")\n# Output: True\n>>> hostname(\"123.5.77.88:31000\")\n# Output: True\n>>> hostname(\"12.12.12.12\")\n# Output: True\n>>> hostname(\"[::1]:22\")\n# Output: True\n>>> hostname(\"dead:beef:0:0:0:0000:42:1\")\n# Output: True\n>>> hostname(\"[0:0:0:0:0:ffff:1.2.3.4]:-65538\")\n# Output: ValidationError(func=hostname, ...)\n>>> hostname(\"[0:&:b:c:@:e:f::]:9999\")\n# Output: ValidationError(func=hostname, ...)\n

Parameters:

Name Type Description Default value str

Hostname string to validate.

required skip_ipv6_addr bool

When hostname string cannot be an IPv6 address.

False skip_ipv4_addr bool

When hostname string cannot be an IPv4 address.

False may_have_port bool

Hostname string may contain port number.

True maybe_simple bool

Hostname string maybe only hyphens and alpha-numerals.

True rfc_1034 bool

Allow trailing dot in domain/host name. Ref: RFC 1034.

False rfc_2782 bool

Domain/Host name is of type service record. Ref: RFC 2782.

False

Returns:

Type Description Literal[True]

If value is a valid hostname.

ValidationError

If value is an invalid hostname.

New in version 0.21.0.

Source code in src/validators/hostname.py
@validator\ndef hostname(\n    value: str,\n    /,\n    *,\n    skip_ipv6_addr: bool = False,\n    skip_ipv4_addr: bool = False,\n    may_have_port: bool = True,\n    maybe_simple: bool = True,\n    rfc_1034: bool = False,\n    rfc_2782: bool = False,\n):\n    \"\"\"Return whether or not given value is a valid hostname.\n\n    Examples:\n        >>> hostname(\"ubuntu-pc:443\")\n        # Output: True\n        >>> hostname(\"this-pc\")\n        # Output: True\n        >>> hostname(\"xn----gtbspbbmkef.xn--p1ai:65535\")\n        # Output: True\n        >>> hostname(\"_example.com\")\n        # Output: True\n        >>> hostname(\"123.5.77.88:31000\")\n        # Output: True\n        >>> hostname(\"12.12.12.12\")\n        # Output: True\n        >>> hostname(\"[::1]:22\")\n        # Output: True\n        >>> hostname(\"dead:beef:0:0:0:0000:42:1\")\n        # Output: True\n        >>> hostname(\"[0:0:0:0:0:ffff:1.2.3.4]:-65538\")\n        # Output: ValidationError(func=hostname, ...)\n        >>> hostname(\"[0:&:b:c:@:e:f::]:9999\")\n        # Output: ValidationError(func=hostname, ...)\n\n    Args:\n        value:\n            Hostname string to validate.\n        skip_ipv6_addr:\n            When hostname string cannot be an IPv6 address.\n        skip_ipv4_addr:\n            When hostname string cannot be an IPv4 address.\n        may_have_port:\n            Hostname string may contain port number.\n        maybe_simple:\n            Hostname string maybe only hyphens and alpha-numerals.\n        rfc_1034:\n            Allow trailing dot in domain/host name.\n            Ref: [RFC 1034](https://www.rfc-editor.org/rfc/rfc1034).\n        rfc_2782:\n            Domain/Host name is of type service record.\n            Ref: [RFC 2782](https://www.rfc-editor.org/rfc/rfc2782).\n\n    Returns:\n        (Literal[True]):\n            If `value` is a valid hostname.\n        (ValidationError):\n            If `value` is an invalid hostname.\n\n    > *New in version 0.21.0*.\n    \"\"\"\n    if not value:\n        return False\n\n    if may_have_port and (host_seg := _port_validator(value)):\n        return (\n            (_simple_hostname_regex().match(host_seg) if maybe_simple else False)\n            or domain(host_seg, rfc_1034=rfc_1034, rfc_2782=rfc_2782)\n            or (False if skip_ipv4_addr else ipv4(host_seg, cidr=False))\n            or (False if skip_ipv6_addr else ipv6(host_seg, cidr=False))\n        )\n\n    return (\n        (_simple_hostname_regex().match(value) if maybe_simple else False)\n        or domain(value, rfc_1034=rfc_1034, rfc_2782=rfc_2782)\n        or (False if skip_ipv4_addr else ipv4(value, cidr=False))\n        or (False if skip_ipv6_addr else ipv6(value, cidr=False))\n    )\n
"},{"location":"references/i18n/","title":"i18n","text":""},{"location":"references/i18n/#validators.i18n.es_cif","title":"validators.i18n.es_cif(value)","text":"

Validate a Spanish CIF.

Each company in Spain prior to 2008 had a distinct CIF and has been discontinued. For more information see wikipedia.org/cif.

The new replacement is to use NIF for absolutely everything. The issue is that there are \"types\" of NIFs now: company, person [citizen or resident] all distinguished by the first character of the DOI. For this reason we will continue to call CIFs NIFs, that are used for companies.

This validator is based on generadordni.es.

Examples:

>>> es_cif('B25162520')\n# Output: True\n>>> es_cif('B25162529')\n# Output: ValidationError(func=es_cif, args=...)\n

Parameters:

Name Type Description Default value str

DOI string which is to be validated.

required

Returns:

Type Description Literal[True]

If value is a valid DOI string.

ValidationError

If value is an invalid DOI string.

New in version 0.13.0.

Source code in src/validators/i18n/es.py
@validator\ndef es_cif(value: str, /):\n    \"\"\"Validate a Spanish CIF.\n\n    Each company in Spain prior to 2008 had a distinct CIF and has been\n    discontinued. For more information see [wikipedia.org/cif][1].\n\n    The new replacement is to use NIF for absolutely everything. The issue is\n    that there are \"types\" of NIFs now: company, person [citizen or resident]\n    all distinguished by the first character of the DOI. For this reason we\n    will continue to call CIFs NIFs, that are used for companies.\n\n    This validator is based on [generadordni.es][2].\n\n    [1]: https://es.wikipedia.org/wiki/C%C3%B3digo_de_identificaci%C3%B3n_fiscal\n    [2]: https://generadordni.es/\n\n    Examples:\n        >>> es_cif('B25162520')\n        # Output: True\n        >>> es_cif('B25162529')\n        # Output: ValidationError(func=es_cif, args=...)\n\n    Args:\n        value:\n            DOI string which is to be validated.\n\n    Returns:\n        (Literal[True]):\n            If `value` is a valid DOI string.\n        (ValidationError):\n            If `value` is an invalid DOI string.\n\n    > *New in version 0.13.0*.\n    \"\"\"\n    if not value or len(value) != 9:\n        return False\n    value = value.upper()\n    table = \"JABCDEFGHI\"\n    first_chr = value[0]\n    doi_body = value[1:8]\n    control = value[8]\n    if not doi_body.isdigit():\n        return False\n    res = (\n        10\n        - sum(\n            # Multiply each positionally even doi\n            # digit by 2 and sum it all together\n            sum(map(int, str(int(char) * 2))) if index % 2 == 0 else int(char)\n            for index, char in enumerate(doi_body)\n        )\n        % 10\n    ) % 10\n    if first_chr in \"ABEH\":  # Number type\n        return str(res) == control\n    if first_chr in \"PSQW\":  # Letter type\n        return table[res] == control\n    return control in {str(res), table[res]} if first_chr in \"CDFGJNRUV\" else False\n
"},{"location":"references/i18n/#validators.i18n.es_doi","title":"validators.i18n.es_doi(value)","text":"

Validate a Spanish DOI.

A DOI in spain is all NIF / CIF / NIE / DNI -- a digital ID. For more information see wikipedia.org/doi. This validator is based on generadordni.es.

Examples:

>>> es_doi('X0095892M')\n# Output: True\n>>> es_doi('X0095892X')\n# Output: ValidationError(func=es_doi, args=...)\n

Parameters:

Name Type Description Default value str

DOI string which is to be validated.

required

Returns:

Type Description Literal[True]

If value is a valid DOI string.

ValidationError

If value is an invalid DOI string.

New in version 0.13.0.

Source code in src/validators/i18n/es.py
@validator\ndef es_doi(value: str, /):\n    \"\"\"Validate a Spanish DOI.\n\n    A DOI in spain is all NIF / CIF / NIE / DNI -- a digital ID.\n    For more information see [wikipedia.org/doi][1]. This validator\n    is based on [generadordni.es][2].\n\n    [1]: https://es.wikipedia.org/wiki/Identificador_de_objeto_digital\n    [2]: https://generadordni.es/\n\n    Examples:\n        >>> es_doi('X0095892M')\n        # Output: True\n        >>> es_doi('X0095892X')\n        # Output: ValidationError(func=es_doi, args=...)\n\n    Args:\n        value:\n            DOI string which is to be validated.\n\n    Returns:\n        (Literal[True]):\n            If `value` is a valid DOI string.\n        (ValidationError):\n            If `value` is an invalid DOI string.\n\n    > *New in version 0.13.0*.\n    \"\"\"\n    return es_nie(value) or es_nif(value) or es_cif(value)\n
"},{"location":"references/i18n/#validators.i18n.es_nie","title":"validators.i18n.es_nie(value)","text":"

Validate a Spanish NIE.

The NIE is a tax identification number in Spain, known in Spanish as the NIE, or more formally the N\u00famero de identidad de extranjero. For more information see wikipedia.org/nie. This validator is based on generadordni.es.

Examples:

>>> es_nie('X0095892M')\n# Output: True\n>>> es_nie('X0095892X')\n# Output: ValidationError(func=es_nie, args=...)\n

Parameters:

Name Type Description Default value str

DOI string which is to be validated.

required

Returns:

Type Description Literal[True]

If value is a valid DOI string.

ValidationError

If value is an invalid DOI string.

New in version 0.13.0.

Source code in src/validators/i18n/es.py
@validator\ndef es_nie(value: str, /):\n    \"\"\"Validate a Spanish NIE.\n\n    The NIE is a tax identification number in Spain, known in Spanish\n    as the NIE, or more formally the N\u00famero de identidad de extranjero.\n    For more information see [wikipedia.org/nie][1]. This validator\n    is based on [generadordni.es][2].\n\n    [1]: https://es.wikipedia.org/wiki/N%C3%BAmero_de_identidad_de_extranjero\n    [2]: https://generadordni.es/\n\n    Examples:\n        >>> es_nie('X0095892M')\n        # Output: True\n        >>> es_nie('X0095892X')\n        # Output: ValidationError(func=es_nie, args=...)\n\n    Args:\n        value:\n            DOI string which is to be validated.\n\n    Returns:\n        (Literal[True]):\n            If `value` is a valid DOI string.\n        (ValidationError):\n            If `value` is an invalid DOI string.\n\n    > *New in version 0.13.0*.\n    \"\"\"\n    number_by_letter = {\"X\": \"0\", \"Y\": \"1\", \"Z\": \"2\"}\n    # NIE must must start with X Y or Z\n    if value and value[0] in number_by_letter:\n        return _nif_nie_validation(value, number_by_letter, {\"X0000000T\"})\n    return False\n
"},{"location":"references/i18n/#validators.i18n.es_nif","title":"validators.i18n.es_nif(value)","text":"

Validate a Spanish NIF.

Each entity, be it person or company in Spain has a distinct NIF. Since we've designated CIF to be a company NIF, this NIF is only for person. For more information see wikipedia.org/nif. This validator is based on generadordni.es.

Examples:

>>> es_nif('26643189N')\n# Output: True\n>>> es_nif('26643189X')\n# Output: ValidationError(func=es_nif, args=...)\n

Parameters:

Name Type Description Default value str

DOI string which is to be validated.

required

Returns:

Type Description Literal[True]

If value is a valid DOI string.

ValidationError

If value is an invalid DOI string.

New in version 0.13.0.

Source code in src/validators/i18n/es.py
@validator\ndef es_nif(value: str, /):\n    \"\"\"Validate a Spanish NIF.\n\n    Each entity, be it person or company in Spain has a distinct NIF. Since\n    we've designated CIF to be a company NIF, this NIF is only for person.\n    For more information see [wikipedia.org/nif][1]. This validator\n    is based on [generadordni.es][2].\n\n    [1]: https://es.wikipedia.org/wiki/N%C3%BAmero_de_identificaci%C3%B3n_fiscal\n    [2]: https://generadordni.es/\n\n    Examples:\n        >>> es_nif('26643189N')\n        # Output: True\n        >>> es_nif('26643189X')\n        # Output: ValidationError(func=es_nif, args=...)\n\n    Args:\n        value:\n            DOI string which is to be validated.\n\n    Returns:\n        (Literal[True]):\n            If `value` is a valid DOI string.\n        (ValidationError):\n            If `value` is an invalid DOI string.\n\n    > *New in version 0.13.0*.\n    \"\"\"\n    number_by_letter = {\"L\": \"0\", \"M\": \"0\", \"K\": \"0\"}\n    special_cases = {\"X0000000T\", \"00000000T\", \"00000001R\"}\n    return _nif_nie_validation(value, number_by_letter, special_cases)\n
"},{"location":"references/i18n/#validators.i18n.fi_business_id","title":"validators.i18n.fi_business_id(value)","text":"

Validate a Finnish Business ID.

Each company in Finland has a distinct business id. For more information see Finnish Trade Register

Examples:

>>> fi_business_id('0112038-9')  # Fast Monkeys Ltd\n# Output: True\n>>> fi_business_id('1234567-8')  # Bogus ID\n# Output: ValidationError(func=fi_business_id, ...)\n

Parameters:

Name Type Description Default value str

Business ID string to be validated.

required

Returns:

Type Description Literal[True]

If value is a valid finnish business id.

ValidationError

If value is an invalid finnish business id.

Note
  • In version 0.5.0:
    • Function renamed from finnish_business_id to fi_business_id

New in version 0.4.0.

Source code in src/validators/i18n/fi.py
@validator\ndef fi_business_id(value: str, /):\n    \"\"\"Validate a Finnish Business ID.\n\n    Each company in Finland has a distinct business id. For more\n    information see [Finnish Trade Register][1]\n\n    [1]: http://en.wikipedia.org/wiki/Finnish_Trade_Register\n\n    Examples:\n        >>> fi_business_id('0112038-9')  # Fast Monkeys Ltd\n        # Output: True\n        >>> fi_business_id('1234567-8')  # Bogus ID\n        # Output: ValidationError(func=fi_business_id, ...)\n\n    Args:\n        value:\n            Business ID string to be validated.\n\n    Returns:\n        (Literal[True]):\n            If `value` is a valid finnish business id.\n        (ValidationError):\n            If `value` is an invalid finnish business id.\n\n    Note:\n        - *In version 0.5.0*:\n            - Function renamed from `finnish_business_id` to `fi_business_id`\n\n    > *New in version 0.4.0*.\n    \"\"\"\n    if not value:\n        return False\n    if not re.match(_business_id_pattern(), value):\n        return False\n    factors = [7, 9, 10, 5, 8, 4, 2]\n    numbers = map(int, value[:7])\n    checksum = int(value[8])\n    modulo = sum(f * n for f, n in zip(factors, numbers)) % 11\n    return (11 - modulo == checksum) or (modulo == checksum == 0)\n
"},{"location":"references/i18n/#validators.i18n.fi_ssn","title":"validators.i18n.fi_ssn(value, /, *, allow_temporal_ssn=True)","text":"

Validate a Finnish Social Security Number.

This validator is based on django-localflavor-fi.

Examples:

>>> fi_ssn('010101-0101')\n# Output: True\n>>> fi_ssn('101010-0102')\n# Output: ValidationError(func=fi_ssn, args=...)\n

Parameters:

Name Type Description Default value str

Social Security Number to be validated.

required allow_temporal_ssn bool

Whether to accept temporal SSN numbers. Temporal SSN numbers are the ones where the serial is in the range [900-999]. By default temporal SSN numbers are valid.

True

Returns:

Type Description Literal[True]

If value is a valid finnish SSN.

ValidationError

If value is an invalid finnish SSN.

New in version 0.5.0.

Source code in src/validators/i18n/fi.py
@validator\ndef fi_ssn(value: str, /, *, allow_temporal_ssn: bool = True):\n    \"\"\"Validate a Finnish Social Security Number.\n\n    This validator is based on [django-localflavor-fi][1].\n\n    [1]: https://github.com/django/django-localflavor-fi/\n\n    Examples:\n        >>> fi_ssn('010101-0101')\n        # Output: True\n        >>> fi_ssn('101010-0102')\n        # Output: ValidationError(func=fi_ssn, args=...)\n\n    Args:\n        value:\n            Social Security Number to be validated.\n        allow_temporal_ssn:\n            Whether to accept temporal SSN numbers. Temporal SSN numbers are the\n            ones where the serial is in the range [900-999]. By default temporal\n            SSN numbers are valid.\n\n    Returns:\n        (Literal[True]):\n            If `value` is a valid finnish SSN.\n        (ValidationError):\n            If `value` is an invalid finnish SSN.\n\n    > *New in version 0.5.0*.\n    \"\"\"\n    if not value:\n        return False\n    ssn_check_marks = \"0123456789ABCDEFHJKLMNPRSTUVWXY\"\n    if not (result := re.match(_ssn_pattern(ssn_check_marks), value)):\n        return False\n    gd = result.groupdict()\n    checksum = int(gd[\"date\"] + gd[\"serial\"])\n    return (\n        int(gd[\"serial\"]) >= 2\n        and (allow_temporal_ssn or int(gd[\"serial\"]) <= 899)\n        and ssn_check_marks[checksum % len(ssn_check_marks)] == gd[\"checksum\"]\n    )\n
"},{"location":"references/i18n/#validators.i18n.fr_department","title":"validators.i18n.fr_department(value)","text":"

Validate a french department number.

Examples:

>>> fr_department(20)  # can be an integer\n# Output: True\n>>> fr_department(\"20\")\n# Output: True\n>>> fr_department(\"971\")  # Guadeloupe\n# Output: True\n>>> fr_department(\"00\")\n# Output: ValidationError(func=fr_department, args=...)\n>>> fr_department('2A')  # Corsica\n# Output: True\n>>> fr_department('2B')\n# Output: True\n>>> fr_department('2C')\n# Output: ValidationError(func=fr_department, args=...)\n

Parameters:

Name Type Description Default value Union[str, int]

French department number to validate.

required

Returns:

Type Description Literal[True]

If value is a valid french department number.

ValidationError

If value is an invalid french department number.

New in version 0.23.0.

Source code in src/validators/i18n/fr.py
@validator\ndef fr_department(value: typing.Union[str, int]):\n    \"\"\"Validate a french department number.\n\n    Examples:\n        >>> fr_department(20)  # can be an integer\n        # Output: True\n        >>> fr_department(\"20\")\n        # Output: True\n        >>> fr_department(\"971\")  # Guadeloupe\n        # Output: True\n        >>> fr_department(\"00\")\n        # Output: ValidationError(func=fr_department, args=...)\n        >>> fr_department('2A')  # Corsica\n        # Output: True\n        >>> fr_department('2B')\n        # Output: True\n        >>> fr_department('2C')\n        # Output: ValidationError(func=fr_department, args=...)\n\n    Args:\n        value:\n            French department number to validate.\n\n    Returns:\n        (Literal[True]):\n            If `value` is a valid french department number.\n        (ValidationError):\n            If `value` is an invalid french department number.\n\n    > *New in version 0.23.0*.\n    \"\"\"\n    if not value:\n        return False\n    if isinstance(value, str):\n        if value in (\"2A\", \"2B\"):  # Corsica\n            return True\n        try:\n            value = int(value)\n        except ValueError:\n            return False\n    return 1 <= value <= 19 or 21 <= value <= 95 or 971 <= value <= 976  # Overseas departments\n
"},{"location":"references/i18n/#validators.i18n.fr_ssn","title":"validators.i18n.fr_ssn(value)","text":"

Validate a french Social Security Number.

Each french citizen has a distinct Social Security Number. For more information see French Social Security Number (sadly unavailable in english).

Examples:

>>> fr_ssn('1 84 12 76 451 089 46')\n# Output: True\n>>> fr_ssn('1 84 12 76 451 089')  # control key is optional\n# Output: True\n>>> fr_ssn('3 84 12 76 451 089 46')  # wrong gender number\n# Output: ValidationError(func=fr_ssn, args=...)\n>>> fr_ssn('1 84 12 76 451 089 47')  # wrong control key\n# Output: ValidationError(func=fr_ssn, args=...)\n

Parameters:

Name Type Description Default value str

French Social Security Number string to validate.

required

Returns:

Type Description Literal[True]

If value is a valid french Social Security Number.

ValidationError

If value is an invalid french Social Security Number.

New in version 0.23.0.

Source code in src/validators/i18n/fr.py
@validator\ndef fr_ssn(value: str):\n    \"\"\"Validate a french Social Security Number.\n\n    Each french citizen has a distinct Social Security Number.\n    For more information see [French Social Security Number][1] (sadly unavailable in english).\n\n    [1]: https://fr.wikipedia.org/wiki/Num%C3%A9ro_de_s%C3%A9curit%C3%A9_sociale_en_France\n\n    Examples:\n        >>> fr_ssn('1 84 12 76 451 089 46')\n        # Output: True\n        >>> fr_ssn('1 84 12 76 451 089')  # control key is optional\n        # Output: True\n        >>> fr_ssn('3 84 12 76 451 089 46')  # wrong gender number\n        # Output: ValidationError(func=fr_ssn, args=...)\n        >>> fr_ssn('1 84 12 76 451 089 47')  # wrong control key\n        # Output: ValidationError(func=fr_ssn, args=...)\n\n    Args:\n        value:\n            French Social Security Number string to validate.\n\n    Returns:\n        (Literal[True]):\n            If `value` is a valid french Social Security Number.\n        (ValidationError):\n            If `value` is an invalid french Social Security Number.\n\n    > *New in version 0.23.0*.\n    \"\"\"\n    if not value:\n        return False\n    matched = re.match(_ssn_pattern(), value)\n    if not matched:\n        return False\n    groups = list(matched.groups())\n    control_key = groups[-1]\n    department = groups[3]\n    if department != \"99\" and not fr_department(department):\n        # 99 stands for foreign born people\n        return False\n    if control_key is None:\n        # no control key provided, no additional check needed\n        return True\n    if len(department) == len(groups[4]):\n        # if the department number is 3 digits long (overseas departments),\n        # the town number must be 2 digits long\n        # and vice versa\n        return False\n    if department in (\"2A\", \"2B\"):\n        # Corsica's department numbers are not in the same range as the others\n        # thus 2A and 2B are replaced by 19 and 18 respectively to compute the control key\n        groups[3] = \"19\" if department == \"2A\" else \"18\"\n    # the control key is valid if it is equal to 97 - (the first 13 digits modulo 97)\n    digits = int(\"\".join(groups[:-1]))\n    return int(control_key) == (97 - (digits % 97))\n
"},{"location":"references/iban/","title":"iban","text":""},{"location":"references/iban/#validators.iban.iban","title":"validators.iban.iban(value)","text":"

Return whether or not given value is a valid IBAN code.

Examples:

>>> iban('DE29100500001061045672')\n# Output: True\n>>> iban('123456')\n# Output: ValidationError(func=iban, ...)\n

Parameters:

Name Type Description Default value str

IBAN string to validate.

required

Returns:

Type Description Literal[True]

If value is a valid IBAN code.

ValidationError

If value is an invalid IBAN code.

New in version 0.8.0

Source code in src/validators/iban.py
@validator\ndef iban(value: str, /):\n    \"\"\"Return whether or not given value is a valid IBAN code.\n\n    Examples:\n        >>> iban('DE29100500001061045672')\n        # Output: True\n        >>> iban('123456')\n        # Output: ValidationError(func=iban, ...)\n\n    Args:\n        value:\n            IBAN string to validate.\n\n    Returns:\n        (Literal[True]):\n            If `value` is a valid IBAN code.\n        (ValidationError):\n            If `value` is an invalid IBAN code.\n\n    > *New in version 0.8.0*\n    \"\"\"\n    return (\n        (re.match(r\"^[A-Z]{2}[0-9]{2}[A-Z0-9]{11,30}$\", value) and _mod_check(value))\n        if value\n        else False\n    )\n
"},{"location":"references/ip_address/","title":"ip_address","text":""},{"location":"references/ip_address/#validators.ip_address.ipv4","title":"validators.ip_address.ipv4(value, /, *, cidr=True, strict=False, host_bit=True)","text":"

Returns whether a given value is a valid IPv4 address.

From Python version 3.9.5 leading zeros are no longer tolerated and are treated as an error. The initial version of ipv4 validator was inspired from WTForms IPAddress validator.

Examples:

>>> ipv4('123.0.0.7')\n# Output: True\n>>> ipv4('1.1.1.1/8')\n# Output: True\n>>> ipv4('900.80.70.11')\n# Output: ValidationError(func=ipv4, args={'value': '900.80.70.11'})\n

Parameters:

Name Type Description Default value str

IP address string to validate.

required cidr bool

IP address string may contain CIDR notation

True strict bool

IP address string is strictly in CIDR notation

False host_bit bool

If False and host bits (along with network bits) are set in the supplied address, this function raises a validation error. ref IPv4Network.

True

Returns:

Type Description Literal[True]

If value is a valid IPv4 address.

ValidationError

If value is an invalid IPv4 address.

Note
  • In version 0.14.0:
    • Add supports for CIDR notation

New in version 0.2.0

Source code in src/validators/ip_address.py
@validator\ndef ipv4(value: str, /, *, cidr: bool = True, strict: bool = False, host_bit: bool = True):\n    \"\"\"Returns whether a given value is a valid IPv4 address.\n\n    From Python version 3.9.5 leading zeros are no longer tolerated\n    and are treated as an error. The initial version of ipv4 validator\n    was inspired from [WTForms IPAddress validator][1].\n\n    [1]: https://github.com/wtforms/wtforms/blob/master/src/wtforms/validators.py\n\n    Examples:\n        >>> ipv4('123.0.0.7')\n        # Output: True\n        >>> ipv4('1.1.1.1/8')\n        # Output: True\n        >>> ipv4('900.80.70.11')\n        # Output: ValidationError(func=ipv4, args={'value': '900.80.70.11'})\n\n    Args:\n        value:\n            IP address string to validate.\n        cidr:\n            IP address string may contain CIDR notation\n        strict:\n            IP address string is strictly in CIDR notation\n        host_bit:\n            If `False` and host bits (along with network bits) _are_ set in the supplied\n            address, this function raises a validation error. ref [IPv4Network][2].\n            [2]: https://docs.python.org/3/library/ipaddress.html#ipaddress.IPv4Network\n\n    Returns:\n        (Literal[True]):\n            If `value` is a valid IPv4 address.\n        (ValidationError):\n            If `value` is an invalid IPv4 address.\n\n    Note:\n        - *In version 0.14.0*:\n            - Add supports for CIDR notation\n\n    > *New in version 0.2.0*\n    \"\"\"\n    if not value:\n        return False\n    try:\n        if cidr:\n            if strict and value.count(\"/\") != 1:\n                raise ValueError(\"IPv4 address was expected in CIDR notation\")\n            return IPv4Network(value, strict=not host_bit)\n        return IPv4Address(value)\n    except (ValueError, AddressValueError, NetmaskValueError):\n        return False\n
"},{"location":"references/ip_address/#validators.ip_address.ipv6","title":"validators.ip_address.ipv6(value, /, *, cidr=True, strict=False, host_bit=True)","text":"

Returns if a given value is a valid IPv6 address.

Including IPv4-mapped IPv6 addresses. The initial version of ipv6 validator was inspired from WTForms IPAddress validator.

Examples:

>>> ipv6('::ffff:192.0.2.128')\n# Output: True\n>>> ipv6('::1/128')\n# Output: True\n>>> ipv6('abc.0.0.1')\n# Output: ValidationError(func=ipv6, args={'value': 'abc.0.0.1'})\n

Parameters:

Name Type Description Default value str

IP address string to validate.

required cidr bool

IP address string may contain CIDR annotation

True strict bool

IP address string is strictly in CIDR notation

False host_bit bool

If False and host bits (along with network bits) are set in the supplied address, this function raises a validation error. ref IPv6Network.

True

Returns:

Type Description Literal[True]

If value is a valid IPv6 address.

ValidationError

If value is an invalid IPv6 address.

Note
  • In version 0.14.0:
    • Add supports for CIDR notation

New in version 0.2.0

Source code in src/validators/ip_address.py
@validator\ndef ipv6(value: str, /, *, cidr: bool = True, strict: bool = False, host_bit: bool = True):\n    \"\"\"Returns if a given value is a valid IPv6 address.\n\n    Including IPv4-mapped IPv6 addresses. The initial version of ipv6 validator\n    was inspired from [WTForms IPAddress validator][1].\n\n    [1]: https://github.com/wtforms/wtforms/blob/master/src/wtforms/validators.py\n\n    Examples:\n        >>> ipv6('::ffff:192.0.2.128')\n        # Output: True\n        >>> ipv6('::1/128')\n        # Output: True\n        >>> ipv6('abc.0.0.1')\n        # Output: ValidationError(func=ipv6, args={'value': 'abc.0.0.1'})\n\n    Args:\n        value:\n            IP address string to validate.\n        cidr:\n            IP address string may contain CIDR annotation\n        strict:\n            IP address string is strictly in CIDR notation\n        host_bit:\n            If `False` and host bits (along with network bits) _are_ set in the supplied\n            address, this function raises a validation error. ref [IPv6Network][2].\n            [2]: https://docs.python.org/3/library/ipaddress.html#ipaddress.IPv6Network\n\n    Returns:\n        (Literal[True]):\n            If `value` is a valid IPv6 address.\n        (ValidationError):\n            If `value` is an invalid IPv6 address.\n\n    Note:\n        - *In version 0.14.0*:\n            - Add supports for CIDR notation\n\n    > *New in version 0.2.0*\n    \"\"\"\n    if not value:\n        return False\n    try:\n        if cidr:\n            if strict and value.count(\"/\") != 1:\n                raise ValueError(\"IPv6 address was expected in CIDR notation\")\n            return IPv6Network(value, strict=not host_bit)\n        return IPv6Address(value)\n    except (ValueError, AddressValueError, NetmaskValueError):\n        return False\n
"},{"location":"references/length/","title":"length","text":""},{"location":"references/length/#validators.length.length","title":"validators.length.length(value, /, *, min_val=None, max_val=None)","text":"

Return whether or not the length of given string is within a specified range.

Examples:

>>> length('something', min_val=2)\n# Output: True\n>>> length('something', min_val=9, max_val=9)\n# Output: True\n>>> length('something', max_val=5)\n# Output: ValidationError(func=length, ...)\n

Parameters:

Name Type Description Default value str

The string to validate.

required min_val Union[int, None]

The minimum required length of the string. If not provided, minimum length will not be checked.

None max_val Union[int, None]

The maximum length of the string. If not provided, maximum length will not be checked.

None

Returns:

Type Description Literal[True]

If len(value) is in between the given conditions.

ValidationError

If len(value) is not in between the given conditions.

Raises:

Type Description ValueError

If either min_val or max_val is negative.

Source code in src/validators/length.py
@validator\ndef length(value: str, /, *, min_val: Union[int, None] = None, max_val: Union[int, None] = None):\n    \"\"\"Return whether or not the length of given string is within a specified range.\n\n    Examples:\n        >>> length('something', min_val=2)\n        # Output: True\n        >>> length('something', min_val=9, max_val=9)\n        # Output: True\n        >>> length('something', max_val=5)\n        # Output: ValidationError(func=length, ...)\n\n    Args:\n        value:\n            The string to validate.\n        min_val:\n            The minimum required length of the string. If not provided,\n            minimum length will not be checked.\n        max_val:\n            The maximum length of the string. If not provided,\n            maximum length will not be checked.\n\n    Returns:\n        (Literal[True]):\n            If `len(value)` is in between the given conditions.\n        (ValidationError):\n            If `len(value)` is not in between the given conditions.\n\n    Raises:\n        (ValueError): If either `min_val` or `max_val` is negative.\n    \"\"\"\n    if min_val is not None and min_val < 0:\n        raise ValueError(\"Length cannot be negative. `min_val` is less than zero.\")\n    if max_val is not None and max_val < 0:\n        raise ValueError(\"Length cannot be negative. `max_val` is less than zero.\")\n\n    return bool(between(len(value), min_val=min_val, max_val=max_val))\n
"},{"location":"references/mac_address/","title":"mac_address","text":""},{"location":"references/mac_address/#validators.mac_address.mac_address","title":"validators.mac_address.mac_address(value)","text":"

Return whether or not given value is a valid MAC address.

This validator is based on WTForms MacAddress validator.

Examples:

>>> mac_address('01:23:45:67:ab:CD')\n# Output: True\n>>> mac_address('00:00:00:00:00')\n# Output: ValidationError(func=mac_address, args={'value': '00:00:00:00:00'})\n

Parameters:

Name Type Description Default value str

MAC address string to validate.

required

Returns:

Type Description Literal[True]

If value is a valid MAC address.

ValidationError

If value is an invalid MAC address.

New in version 0.2.0.

Source code in src/validators/mac_address.py
@validator\ndef mac_address(value: str, /):\n    \"\"\"Return whether or not given value is a valid MAC address.\n\n    This validator is based on [WTForms MacAddress validator][1].\n\n    [1]: https://github.com/wtforms/wtforms/blob/master/src/wtforms/validators.py#L482\n\n    Examples:\n        >>> mac_address('01:23:45:67:ab:CD')\n        # Output: True\n        >>> mac_address('00:00:00:00:00')\n        # Output: ValidationError(func=mac_address, args={'value': '00:00:00:00:00'})\n\n    Args:\n        value:\n            MAC address string to validate.\n\n    Returns:\n        (Literal[True]):\n            If `value` is a valid MAC address.\n        (ValidationError):\n            If `value` is an invalid MAC address.\n\n    > *New in version 0.2.0*.\n    \"\"\"\n    return re.match(r\"^([0-9A-Fa-f]{2}[:-]){5}([0-9A-Fa-f]{2})$\", value) if value else False\n
"},{"location":"references/slug/","title":"slug","text":""},{"location":"references/slug/#validators.slug.slug","title":"validators.slug.slug(value)","text":"

Validate whether or not given value is valid slug.

Valid slug can contain only lowercase alphanumeric characters and hyphens. It starts and ends with these lowercase alphanumeric characters.

Examples:

>>> slug('my-slug-2134')\n# Output: True\n>>> slug('my.slug')\n# Output: ValidationError(func=slug, args={'value': 'my.slug'})\n

Parameters:

Name Type Description Default value str

Slug string to validate.

required

Returns:

Type Description Literal[True]

If value is a valid slug.

ValidationError

If value is an invalid slug.

New in version 0.6.0.

Source code in src/validators/slug.py
@validator\ndef slug(value: str, /):\n    \"\"\"Validate whether or not given value is valid slug.\n\n    Valid slug can contain only lowercase alphanumeric characters and hyphens.\n    It starts and ends with these lowercase alphanumeric characters.\n\n    Examples:\n        >>> slug('my-slug-2134')\n        # Output: True\n        >>> slug('my.slug')\n        # Output: ValidationError(func=slug, args={'value': 'my.slug'})\n\n    Args:\n        value:\n            Slug string to validate.\n\n    Returns:\n        (Literal[True]):\n            If `value` is a valid slug.\n        (ValidationError):\n            If `value` is an invalid slug.\n\n    > *New in version 0.6.0*.\n    \"\"\"\n    return re.match(r\"^[a-z0-9]+(?:-[a-z0-9]+)*$\", value) if value else False\n
"},{"location":"references/url/","title":"url","text":""},{"location":"references/url/#validators.url.url","title":"validators.url.url(value, /, *, skip_ipv6_addr=False, skip_ipv4_addr=False, may_have_port=True, simple_host=False, strict_query=True, rfc_1034=False, rfc_2782=False)","text":"

Return whether or not given value is a valid URL.

This validator was inspired from URL validator of dperini. The following diagram is from urlly.

    foo://admin:hunter1@example.com:8042/over/there?name=ferret#nose\n    \\_/   \\___/ \\_____/ \\_________/ \\__/\\_________/ \\_________/ \\__/\n     |      |       |       |        |       |          |         |\n  scheme username password hostname port    path      query    fragment\n

Examples:

>>> url('http://duck.com')\n# Output: True\n>>> url('ftp://foobar.dk')\n# Output: True\n>>> url('http://10.0.0.1')\n# Output: True\n>>> url('http://example.com/\">user@example.com')\n# Output: ValidationError(func=url, ...)\n

Parameters:

Name Type Description Default value str

URL string to validate.

required skip_ipv6_addr bool

When URL string cannot contain an IPv6 address.

False skip_ipv4_addr bool

When URL string cannot contain an IPv4 address.

False may_have_port bool

URL string may contain port number.

True simple_host bool

URL string maybe only hyphens and alpha-numerals.

False strict_query bool

Fail validation on query string parsing error.

True rfc_1034 bool

Allow trailing dot in domain/host name. Ref: RFC 1034.

False rfc_2782 bool

Domain/Host name is of type service record. Ref: RFC 2782.

False

Returns:

Type Description Literal[True]

If value is a valid slug.

ValidationError

If value is an invalid slug.

Note
  • In version 0.11.3:
    • Added support for URLs containing localhost.
  • In version 0.11.0:
    • Made the regular expression case insensitive.
  • In version 0.10.3:
    • Added a public parameter.
  • In version 0.10.2:
    • Added support for various exotic URLs.
    • Fixed various false positives.

New in version 0.2.0.

Source code in src/validators/url.py
@validator\ndef url(\n    value: str,\n    /,\n    *,\n    skip_ipv6_addr: bool = False,\n    skip_ipv4_addr: bool = False,\n    may_have_port: bool = True,\n    simple_host: bool = False,\n    strict_query: bool = True,\n    rfc_1034: bool = False,\n    rfc_2782: bool = False,\n):\n    r\"\"\"Return whether or not given value is a valid URL.\n\n    This validator was inspired from [URL validator of dperini][1].\n    The following diagram is from [urlly][2].\n\n            foo://admin:hunter1@example.com:8042/over/there?name=ferret#nose\n            \\_/   \\___/ \\_____/ \\_________/ \\__/\\_________/ \\_________/ \\__/\n             |      |       |       |        |       |          |         |\n          scheme username password hostname port    path      query    fragment\n\n    [1]: https://gist.github.com/dperini/729294\n    [2]: https://github.com/treeform/urlly\n\n    Examples:\n        >>> url('http://duck.com')\n        # Output: True\n        >>> url('ftp://foobar.dk')\n        # Output: True\n        >>> url('http://10.0.0.1')\n        # Output: True\n        >>> url('http://example.com/\">user@example.com')\n        # Output: ValidationError(func=url, ...)\n\n    Args:\n        value:\n            URL string to validate.\n        skip_ipv6_addr:\n            When URL string cannot contain an IPv6 address.\n        skip_ipv4_addr:\n            When URL string cannot contain an IPv4 address.\n        may_have_port:\n            URL string may contain port number.\n        simple_host:\n            URL string maybe only hyphens and alpha-numerals.\n        strict_query:\n            Fail validation on query string parsing error.\n        rfc_1034:\n            Allow trailing dot in domain/host name.\n            Ref: [RFC 1034](https://www.rfc-editor.org/rfc/rfc1034).\n        rfc_2782:\n            Domain/Host name is of type service record.\n            Ref: [RFC 2782](https://www.rfc-editor.org/rfc/rfc2782).\n\n    Returns:\n        (Literal[True]):\n            If `value` is a valid slug.\n        (ValidationError):\n            If `value` is an invalid slug.\n\n    Note:\n        - *In version 0.11.3*:\n            - Added support for URLs containing localhost.\n        - *In version 0.11.0*:\n            - Made the regular expression case insensitive.\n        - *In version 0.10.3*:\n            - Added a `public` parameter.\n        - *In version 0.10.2*:\n            - Added support for various exotic URLs.\n            - Fixed various false positives.\n\n    > *New in version 0.2.0*.\n    \"\"\"\n    if not value or re.search(r\"\\s\", value):\n        # url must not contain any white\n        # spaces, they must be encoded\n        return False\n\n    try:\n        scheme, netloc, path, query, fragment = urlsplit(value)\n    except ValueError:\n        return False\n\n    return (\n        _validate_scheme(scheme)\n        and _validate_netloc(\n            netloc,\n            skip_ipv6_addr,\n            skip_ipv4_addr,\n            may_have_port,\n            simple_host,\n            rfc_1034,\n            rfc_2782,\n        )\n        and _validate_optionals(path, query, fragment, strict_query)\n    )\n
"},{"location":"references/utils/","title":"utils","text":""},{"location":"references/utils/#validators.utils.ValidationError","title":"validators.utils.ValidationError","text":"

Bases: Exception

Exception class when validation failure occurs.

Source code in src/validators/utils.py
class ValidationError(Exception):\n    \"\"\"Exception class when validation failure occurs.\"\"\"\n\n    def __init__(self, function: Callable[..., Any], arg_dict: Dict[str, Any], message: str = \"\"):\n        \"\"\"Initialize Validation Failure.\"\"\"\n        if message:\n            self.reason = message\n        self.func = function\n        self.__dict__.update(arg_dict)\n\n    def __repr__(self):\n        \"\"\"Repr Validation Failure.\"\"\"\n        return (\n            f\"ValidationError(func={self.func.__name__}, \"\n            + f\"args={({k: v for (k, v) in self.__dict__.items() if k != 'func'})})\"\n        )\n\n    def __str__(self):\n        \"\"\"Str Validation Failure.\"\"\"\n        return repr(self)\n\n    def __bool__(self):\n        \"\"\"Bool Validation Failure.\"\"\"\n        return False\n
"},{"location":"references/utils/#validators.utils.ValidationError.__bool__","title":"__bool__()","text":"

Bool Validation Failure.

Source code in src/validators/utils.py
def __bool__(self):\n    \"\"\"Bool Validation Failure.\"\"\"\n    return False\n
"},{"location":"references/utils/#validators.utils.ValidationError.__init__","title":"__init__(function, arg_dict, message='')","text":"

Initialize Validation Failure.

Source code in src/validators/utils.py
def __init__(self, function: Callable[..., Any], arg_dict: Dict[str, Any], message: str = \"\"):\n    \"\"\"Initialize Validation Failure.\"\"\"\n    if message:\n        self.reason = message\n    self.func = function\n    self.__dict__.update(arg_dict)\n
"},{"location":"references/utils/#validators.utils.ValidationError.__repr__","title":"__repr__()","text":"

Repr Validation Failure.

Source code in src/validators/utils.py
def __repr__(self):\n    \"\"\"Repr Validation Failure.\"\"\"\n    return (\n        f\"ValidationError(func={self.func.__name__}, \"\n        + f\"args={({k: v for (k, v) in self.__dict__.items() if k != 'func'})})\"\n    )\n
"},{"location":"references/utils/#validators.utils.ValidationError.__str__","title":"__str__()","text":"

Str Validation Failure.

Source code in src/validators/utils.py
def __str__(self):\n    \"\"\"Str Validation Failure.\"\"\"\n    return repr(self)\n
"},{"location":"references/utils/#validators.utils.validator","title":"validators.utils.validator(func)","text":"

A decorator that makes given function validator.

Whenever the given func returns False this decorator returns ValidationError object.

Examples:

>>> @validator\n... def even(value):\n...     return not (value % 2)\n>>> even(4)\n# Output: True\n>>> even(5)\n# Output: ValidationError(func=even, args={'value': 5})\n

Parameters:

Name Type Description Default func Callable[..., Any]

Function which is to be decorated.

required

Returns:

Type Description Callable[..., ValidationError | Literal[True]]

A decorator which returns either ValidationError or Literal[True].

New in version 2013.10.21.

Source code in src/validators/utils.py
def validator(func: Callable[..., Any]):\n    \"\"\"A decorator that makes given function validator.\n\n    Whenever the given `func` returns `False` this\n    decorator returns `ValidationError` object.\n\n    Examples:\n        >>> @validator\n        ... def even(value):\n        ...     return not (value % 2)\n        >>> even(4)\n        # Output: True\n        >>> even(5)\n        # Output: ValidationError(func=even, args={'value': 5})\n\n    Args:\n        func:\n            Function which is to be decorated.\n\n    Returns:\n        (Callable[..., ValidationError | Literal[True]]):\n            A decorator which returns either `ValidationError`\n            or `Literal[True]`.\n\n    > *New in version 2013.10.21*.\n    \"\"\"\n\n    @wraps(func)\n    def wrapper(*args: Any, **kwargs: Any):\n        try:\n            return (\n                True\n                if func(*args, **kwargs)\n                else ValidationError(func, _func_args_as_dict(func, *args, **kwargs))\n            )\n        except Exception as exp:\n            return ValidationError(func, _func_args_as_dict(func, *args, **kwargs), str(exp))\n\n    return wrapper\n
"},{"location":"references/uuid/","title":"uuid","text":""},{"location":"references/uuid/#validators.uuid.uuid","title":"validators.uuid.uuid(value)","text":"

Return whether or not given value is a valid UUID-v4 string.

This validator is based on WTForms UUID validator.

Examples:

>>> uuid('2bc1c94f-0deb-43e9-92a1-4775189ec9f8')\n# Output: True\n>>> uuid('2bc1c94f 0deb-43e9-92a1-4775189ec9f8')\n# Output: ValidationError(func=uuid, ...)\n

Parameters:

Name Type Description Default value Union[str, UUID]

UUID string or object to validate.

required

Returns:

Type Description Literal[True]

If value is a valid UUID.

ValidationError

If value is an invalid UUID.

New in version 0.2.0.

Source code in src/validators/uuid.py
@validator\ndef uuid(value: Union[str, UUID], /):\n    \"\"\"Return whether or not given value is a valid UUID-v4 string.\n\n    This validator is based on [WTForms UUID validator][1].\n\n    [1]: https://github.com/wtforms/wtforms/blob/master/src/wtforms/validators.py#L539\n\n    Examples:\n        >>> uuid('2bc1c94f-0deb-43e9-92a1-4775189ec9f8')\n        # Output: True\n        >>> uuid('2bc1c94f 0deb-43e9-92a1-4775189ec9f8')\n        # Output: ValidationError(func=uuid, ...)\n\n    Args:\n        value:\n            UUID string or object to validate.\n\n    Returns:\n        (Literal[True]):\n            If `value` is a valid UUID.\n        (ValidationError):\n            If `value` is an invalid UUID.\n\n    > *New in version 0.2.0*.\n    \"\"\"\n    if not value:\n        return False\n    if isinstance(value, UUID):\n        return True\n    try:\n        return UUID(value) or re.match(\n            r\"^[0-9a-fA-F]{8}-([0-9a-fA-F]{4}-){3}[0-9a-fA-F]{12}$\", value\n        )\n    except ValueError:\n        return False\n
"}]} \ No newline at end of file diff --git a/0.23/sitemap.xml.gz b/0.23/sitemap.xml.gz index a0ce0657130ca01c5869ee10f1dcbe4c243d9449..cbf637cc749fe8660f8909720f4df948e09e87d9 100644 GIT binary patch delta 15 WcmX@lbe@S#zMF$%LFGm^PeuSIKm>gN delta 15 WcmX@lbe@S#zMF&Nk;_IlPeuSI!vu-| diff --git a/0.23/validators.1 b/0.23/validators.1 index f4e8f61b..8b121ecc 100644 --- a/0.23/validators.1 +++ b/0.23/validators.1 @@ -27,7 +27,7 @@ level margin: \\n[rst2man-indent\\n[rst2man-indent-level]] .\" new: \\n[rst2man-indent\\n[rst2man-indent-level]] .in \\n[rst2man-indent\\n[rst2man-indent-level]]u .. -.TH "VALIDATORS" "1" "Mar 19, 2024" "0.23.0" "validators" +.TH "VALIDATORS" "1" "Mar 19, 2024" "0.23.1" "validators" .SH NAME validators \- Python Data Validation for Humans™ .sp @@ -120,10 +120,9 @@ If \fIvalue\fP is not in between the given conditions. .B Raises .INDENT 7.0 .IP \(bu 2 -\fBValueError\fP \-\- If both \fImin_val\fP and \fImax_val\fP are \fINone\fP, - or if \fImin_val\fP is greater than \fImax_val\fP\&. +\fB(\fP\fBValueError\fP\fB)\fP \-\- If \fImin_val\fP is greater than \fImax_val\fP\&. .IP \(bu 2 -\fBTypeError\fP \-\- If there\(aqs a type mismatch before comparison. +\fB(\fP\fBTypeError\fP\fB)\fP \-\- If there\(aqs a type mismatch during comparison. .UNINDENT .UNINDENT .sp @@ -134,12 +133,10 @@ If \fIvalue\fP is not in between the given conditions. .IP \(bu 2 \fIPossibleValueTypes\fP = \fITypeVar(\(dqPossibleValueTypes\(dq, int, float, str, datetime)\fP .IP \(bu 2 -Either one of \fImin_val\fP or \fImax_val\fP must be provided. +If neither \fImin_val\fP nor \fImax_val\fP is provided, result will always be \fITrue\fP\&. .UNINDENT .UNINDENT .UNINDENT -.sp -> \fINew in version 0.2.0\fP\&. .UNINDENT .INDENT 0.0 .TP @@ -199,10 +196,9 @@ If \fIvalue\fP is not in between the given conditions. .B Raises .INDENT 7.0 .IP \(bu 2 -\fBValueError\fP \-\- If both \fImin_val\fP and \fImax_val\fP are \fINone\fP, - or if \fImin_val\fP is greater than \fImax_val\fP\&. +\fB(\fP\fBValueError\fP\fB)\fP \-\- If \fImin_val\fP is greater than \fImax_val\fP\&. .IP \(bu 2 -\fBTypeError\fP \-\- If there\(aqs a type mismatch before comparison. +\fB(\fP\fBTypeError\fP\fB)\fP \-\- If there\(aqs a type mismatch during comparison. .UNINDENT .UNINDENT .sp @@ -213,12 +209,86 @@ If \fIvalue\fP is not in between the given conditions. .IP \(bu 2 \fIPossibleValueTypes\fP = \fITypeVar(\(dqPossibleValueTypes\(dq, int, float, str, datetime)\fP .IP \(bu 2 -Either one of \fImin_val\fP or \fImax_val\fP must be provided. +If neither \fImin_val\fP nor \fImax_val\fP is provided, result will always be \fITrue\fP\&. .UNINDENT .UNINDENT .UNINDENT +.UNINDENT +.INDENT 0.0 +.TP +.B validators.between.between(value: PossibleValueTypes, /, *, min_val: PossibleValueTypes | AbsMin | None = None, max_val: PossibleValueTypes | AbsMax | None = None) +Validate that a number is between minimum and/or maximum value. .sp -> \fINew in version 0.2.0\fP\&. +This will work with any comparable type, such as floats, decimals and dates +not just integers. This validator is originally based on [WTForms\-NumberRange\-Validator][1]. +.sp +[1]: \fI\%https://github.com/wtforms/wtforms/blob/master/src/wtforms/validators.py#L166\-L220\fP +.sp +Examples +.sp +.nf +.ft C +>>> from datetime import datetime +>>> between(5, min_val=2) +# Output: True +>>> between(13.2, min_val=13, max_val=14) +# Output: True +>>> between(500, max_val=400) +# Output: ValidationError(func=between, args=...) +>>> between( +\&... datetime(2000, 11, 11), +\&... min_val=datetime(1999, 11, 11) +\&... ) +# Output: True +.ft P +.fi +.INDENT 7.0 +.TP +.B Parameters +.INDENT 7.0 +.IP \(bu 2 +\fBvalue\fP \-\- Value which is to be compared. +.IP \(bu 2 +\fBmin_val\fP \-\- The minimum required value of the number. +If not provided, minimum value will not be checked. +.IP \(bu 2 +\fBmax_val\fP \-\- The maximum value of the number. +If not provided, maximum value will not be checked. +.UNINDENT +.TP +.B Returns +If \fIvalue\fP is in between the given conditions. +(ValidationError): +.INDENT 7.0 +.INDENT 3.5 +If \fIvalue\fP is not in between the given conditions. +.UNINDENT +.UNINDENT + +.TP +.B Return type +(Literal[True]) +.TP +.B Raises +.INDENT 7.0 +.IP \(bu 2 +\fB(\fP\fBValueError\fP\fB)\fP \-\- If \fImin_val\fP is greater than \fImax_val\fP\&. +.IP \(bu 2 +\fB(\fP\fBTypeError\fP\fB)\fP \-\- If there\(aqs a type mismatch during comparison. +.UNINDENT +.UNINDENT +.sp +\fBNOTE:\fP +.INDENT 7.0 +.INDENT 3.5 +.INDENT 0.0 +.IP \(bu 2 +\fIPossibleValueTypes\fP = \fITypeVar(\(dqPossibleValueTypes\(dq, int, float, str, datetime)\fP +.IP \(bu 2 +If neither \fImin_val\fP nor \fImax_val\fP is provided, result will always be \fITrue\fP\&. +.UNINDENT +.UNINDENT +.UNINDENT .UNINDENT .SS btc_address .INDENT 0.0 @@ -294,6 +364,46 @@ If \fIvalue\fP is an invalid bitcoin address. .UNINDENT .UNINDENT +.TP +.B Return type +(Literal[True]) +.UNINDENT +.sp +> \fINew in version 0.18.0\fP\&. +.UNINDENT +.INDENT 0.0 +.TP +.B validators.btc_address.btc_address(value: str, /) +Return whether or not given value is a valid bitcoin address. +.sp +Full validation is implemented for P2PKH and P2SH addresses. +For segwit addresses a regexp is used to provide a reasonable +estimate on whether the address is valid. +.sp +Examples +.sp +.nf +.ft C +>>> btc_address(\(aq3Cwgr2g7vsi1bXDUkpEnVoRLA9w4FZfC69\(aq) +# Output: True +>>> btc_address(\(aq1BvBMsEYstWetqTFn5Au4m4GFg7xJaNVN2\(aq) +# Output: ValidationError(func=btc_address, args=...) +.ft P +.fi +.INDENT 7.0 +.TP +.B Parameters +\fBvalue\fP \-\- Bitcoin address string to validate. +.TP +.B Returns +If \fIvalue\fP is a valid bitcoin address. +(ValidationError): +.INDENT 7.0 +.INDENT 3.5 +If \fIvalue\fP is an invalid bitcoin address. +.UNINDENT +.UNINDENT + .TP .B Return type (Literal[True]) @@ -304,6 +414,42 @@ If \fIvalue\fP is an invalid bitcoin address. .SS card .INDENT 0.0 .TP +.B validators.card.visa(value: str, /) +Return whether or not given value is a valid Visa card number. +.sp +Examples +.sp +.nf +.ft C +>>> visa(\(aq4242424242424242\(aq) +# Output: True +>>> visa(\(aq2223003122003222\(aq) +# Output: ValidationError(func=visa, args={\(aqvalue\(aq: \(aq2223003122003222\(aq}) +.ft P +.fi +.INDENT 7.0 +.TP +.B Parameters +\fBvalue\fP \-\- Visa card number string to validate +.TP +.B Returns +If \fIvalue\fP is a valid Visa card number. +(ValidationError): +.INDENT 7.0 +.INDENT 3.5 +If \fIvalue\fP is an invalid Visa card number. +.UNINDENT +.UNINDENT + +.TP +.B Return type +(Literal[True]) +.UNINDENT +.sp +> \fINew in version 0.15.0\fP\&. +.UNINDENT +.INDENT 0.0 +.TP .B validators.card.amex(value: str, /) Return whether or not given value is a valid American Express card number. .sp @@ -982,6 +1128,56 @@ If \fIvalue\fP is an invalid country code. .UNINDENT .UNINDENT +.TP +.B Return type +(Literal[True]) +.UNINDENT +.UNINDENT +.INDENT 0.0 +.TP +.B validators.country_code.country_code(value: str, /, *, iso_format: str = \(aqauto\(aq) +Validates given country code. +.sp +This performs a case\-sensitive [ISO 3166][1] country code validation. +.sp +[1]: \fI\%https://www.iso.org/iso\-3166\-country\-codes.html\fP +.sp +Examples +.sp +.nf +.ft C +>>> country_code(\(aqGB\(aq, iso_format=\(aqalpha3\(aq) +# Output: False +>>> country_code(\(aqUSA\(aq) +# Output: True +>>> country_code(\(aq840\(aq, iso_format=\(aqnumeric\(aq) +# Output: True +>>> country_code(\(aqiN\(aq, iso_format=\(aqalpha2\(aq) +# Output: False +>>> country_code(\(aqZWE\(aq, iso_format=\(aqalpha3\(aq) +# Output: True +.ft P +.fi +.INDENT 7.0 +.TP +.B Parameters +.INDENT 7.0 +.IP \(bu 2 +\fBvalue\fP \-\- Country code string to validate. +.IP \(bu 2 +\fBiso_format\fP \-\- ISO format to be used. Available options are: +\fIauto\fP, \fIalpha2\fP, \fIalpha3\fP and \fInumeric\fP\&. +.UNINDENT +.TP +.B Returns +If \fIvalue\fP is a valid country code. +(ValidationError): +.INDENT 7.0 +.INDENT 3.5 +If \fIvalue\fP is an invalid country code. +.UNINDENT +.UNINDENT + .TP .B Return type (Literal[True]) @@ -1118,28 +1314,22 @@ Added support for internationalized domain name (IDN) validation. .sp > \fINew in version 0.9.0\fP\&. .UNINDENT -.SS email .INDENT 0.0 .TP -.B validators.email.email(value: str, /, *, ipv6_address: bool = False, ipv4_address: bool = False, simple_host: bool = False, rfc_1034: bool = False, rfc_2782: bool = False) -Validate an email address. -.sp -This was inspired from [Django\(aqs email validator][1]. -Also ref: [RFC 1034][2], [RFC 5321][3] and [RFC 5322][4]. -.sp -[1]: \fI\%https://github.com/django/django/blob/main/django/core/validators.py#L174\fP -[2]: \fI\%https://www.rfc\-editor.org/rfc/rfc1034\fP -[3]: \fI\%https://www.rfc\-editor.org/rfc/rfc5321\fP -[4]: \fI\%https://www.rfc\-editor.org/rfc/rfc5322\fP +.B validators.domain.domain(value: str, /, *, rfc_1034: bool = False, rfc_2782: bool = False) +Return whether or not given value is a valid domain. .sp Examples .sp .nf .ft C ->>> email(\(aqsomeone@example.com\(aq) +>>> domain(\(aqexample.com\(aq) +# Output: True +>>> domain(\(aqexample.com/\(aq) +# Output: ValidationError(func=domain, ...) +>>> # Supports IDN domains as well:: +>>> domain(\(aqxn\-\-\-\-gtbspbbmkef.xn\-\-p1ai\(aq) # Output: True ->>> email(\(aqbogus@@\(aq) -# Output: ValidationError(email=email, args={\(aqvalue\(aq: \(aqbogus@@\(aq}) .ft P .fi .INDENT 7.0 @@ -1147,13 +1337,7 @@ Examples .B Parameters .INDENT 7.0 .IP \(bu 2 -\fBvalue\fP \-\- eMail string to validate. -.IP \(bu 2 -\fBipv6_address\fP \-\- When the domain part is an IPv6 address. -.IP \(bu 2 -\fBipv4_address\fP \-\- When the domain part is an IPv4 address. -.IP \(bu 2 -\fBsimple_host\fP \-\- When the domain part is a simple hostname. +\fBvalue\fP \-\- Domain string to validate. .IP \(bu 2 \fBrfc_1034\fP \-\- Allow trailing dot in domain name. Ref: [RFC 1034](\fI\%https://www.rfc\-editor.org/rfc/rfc1034\fP). @@ -1163,11 +1347,11 @@ Ref: [RFC 2782](\fI\%https://www.rfc\-editor.org/rfc/rfc2782\fP). .UNINDENT .TP .B Returns -If \fIvalue\fP is a valid eMail. +If \fIvalue\fP is a valid domain name. (ValidationError): .INDENT 7.0 .INDENT 3.5 -If \fIvalue\fP is an invalid eMail. +If \fIvalue\fP is an invalid domain name. .UNINDENT .UNINDENT @@ -1176,8 +1360,26 @@ If \fIvalue\fP is an invalid eMail. (Literal[True]) .UNINDENT .sp -> \fINew in version 0.1.0\fP\&. +\fBNOTE:\fP +.INDENT 7.0 +.INDENT 3.5 +.INDENT 0.0 +.IP \(bu 2 +.INDENT 2.0 +.TP +.B \fIIn version 0.10.0\fP: +.INDENT 7.0 +.IP \(bu 2 +Added support for internationalized domain name (IDN) validation. +.UNINDENT .UNINDENT +.UNINDENT +.UNINDENT +.UNINDENT +.sp +> \fINew in version 0.9.0\fP\&. +.UNINDENT +.SS email .INDENT 0.0 .TP .B validators.email.email(value: str, /, *, ipv6_address: bool = False, ipv4_address: bool = False, simple_host: bool = False, rfc_1034: bool = False, rfc_2782: bool = False) @@ -1237,7 +1439,165 @@ If \fIvalue\fP is an invalid eMail. .sp > \fINew in version 0.1.0\fP\&. .UNINDENT -.SS hashes +.INDENT 0.0 +.TP +.B validators.email.email(value: str, /, *, ipv6_address: bool = False, ipv4_address: bool = False, simple_host: bool = False, rfc_1034: bool = False, rfc_2782: bool = False) +Validate an email address. +.sp +This was inspired from [Django\(aqs email validator][1]. +Also ref: [RFC 1034][2], [RFC 5321][3] and [RFC 5322][4]. +.sp +[1]: \fI\%https://github.com/django/django/blob/main/django/core/validators.py#L174\fP +[2]: \fI\%https://www.rfc\-editor.org/rfc/rfc1034\fP +[3]: \fI\%https://www.rfc\-editor.org/rfc/rfc5321\fP +[4]: \fI\%https://www.rfc\-editor.org/rfc/rfc5322\fP +.sp +Examples +.sp +.nf +.ft C +>>> email(\(aqsomeone@example.com\(aq) +# Output: True +>>> email(\(aqbogus@@\(aq) +# Output: ValidationError(email=email, args={\(aqvalue\(aq: \(aqbogus@@\(aq}) +.ft P +.fi +.INDENT 7.0 +.TP +.B Parameters +.INDENT 7.0 +.IP \(bu 2 +\fBvalue\fP \-\- eMail string to validate. +.IP \(bu 2 +\fBipv6_address\fP \-\- When the domain part is an IPv6 address. +.IP \(bu 2 +\fBipv4_address\fP \-\- When the domain part is an IPv4 address. +.IP \(bu 2 +\fBsimple_host\fP \-\- When the domain part is a simple hostname. +.IP \(bu 2 +\fBrfc_1034\fP \-\- Allow trailing dot in domain name. +Ref: [RFC 1034](\fI\%https://www.rfc\-editor.org/rfc/rfc1034\fP). +.IP \(bu 2 +\fBrfc_2782\fP \-\- Domain name is of type service record. +Ref: [RFC 2782](\fI\%https://www.rfc\-editor.org/rfc/rfc2782\fP). +.UNINDENT +.TP +.B Returns +If \fIvalue\fP is a valid eMail. +(ValidationError): +.INDENT 7.0 +.INDENT 3.5 +If \fIvalue\fP is an invalid eMail. +.UNINDENT +.UNINDENT + +.TP +.B Return type +(Literal[True]) +.UNINDENT +.sp +> \fINew in version 0.1.0\fP\&. +.UNINDENT +.INDENT 0.0 +.TP +.B validators.email.email(value: str, /, *, ipv6_address: bool = False, ipv4_address: bool = False, simple_host: bool = False, rfc_1034: bool = False, rfc_2782: bool = False) +Validate an email address. +.sp +This was inspired from [Django\(aqs email validator][1]. +Also ref: [RFC 1034][2], [RFC 5321][3] and [RFC 5322][4]. +.sp +[1]: \fI\%https://github.com/django/django/blob/main/django/core/validators.py#L174\fP +[2]: \fI\%https://www.rfc\-editor.org/rfc/rfc1034\fP +[3]: \fI\%https://www.rfc\-editor.org/rfc/rfc5321\fP +[4]: \fI\%https://www.rfc\-editor.org/rfc/rfc5322\fP +.sp +Examples +.sp +.nf +.ft C +>>> email(\(aqsomeone@example.com\(aq) +# Output: True +>>> email(\(aqbogus@@\(aq) +# Output: ValidationError(email=email, args={\(aqvalue\(aq: \(aqbogus@@\(aq}) +.ft P +.fi +.INDENT 7.0 +.TP +.B Parameters +.INDENT 7.0 +.IP \(bu 2 +\fBvalue\fP \-\- eMail string to validate. +.IP \(bu 2 +\fBipv6_address\fP \-\- When the domain part is an IPv6 address. +.IP \(bu 2 +\fBipv4_address\fP \-\- When the domain part is an IPv4 address. +.IP \(bu 2 +\fBsimple_host\fP \-\- When the domain part is a simple hostname. +.IP \(bu 2 +\fBrfc_1034\fP \-\- Allow trailing dot in domain name. +Ref: [RFC 1034](\fI\%https://www.rfc\-editor.org/rfc/rfc1034\fP). +.IP \(bu 2 +\fBrfc_2782\fP \-\- Domain name is of type service record. +Ref: [RFC 2782](\fI\%https://www.rfc\-editor.org/rfc/rfc2782\fP). +.UNINDENT +.TP +.B Returns +If \fIvalue\fP is a valid eMail. +(ValidationError): +.INDENT 7.0 +.INDENT 3.5 +If \fIvalue\fP is an invalid eMail. +.UNINDENT +.UNINDENT + +.TP +.B Return type +(Literal[True]) +.UNINDENT +.sp +> \fINew in version 0.1.0\fP\&. +.UNINDENT +.SS hashes +.INDENT 0.0 +.TP +.B validators.hashes.sha512(value: str, /) +Return whether or not given value is a valid SHA512 hash. +.sp +Examples +.sp +.nf +.ft C +>>> sha512( +\&... \(aqcf83e1357eefb8bdf1542850d66d8007d620e4050b5715dc83f4a921d36ce\(aq +\&... \(aq9ce47d0d13c5d85f2b0ff8318d2877eec2f63b931bd47417a81a538327af9\(aq +\&... \(aq27da3e\(aq +\&... ) +# Output: True +>>> sha512(\(aq900zz11\(aq) +# Output: ValidationError(func=sha512, args={\(aqvalue\(aq: \(aq900zz11\(aq}) +.ft P +.fi +.INDENT 7.0 +.TP +.B Parameters +\fBvalue\fP \-\- SHA512 string to validate. +.TP +.B Returns +If \fIvalue\fP is a valid SHA512 hash. +(ValidationError): +.INDENT 7.0 +.INDENT 3.5 +If \fIvalue\fP is an invalid SHA512 hash. +.UNINDENT +.UNINDENT + +.TP +.B Return type +(Literal[True]) +.UNINDENT +.sp +> \fINew in version 0.12.1\fP +.UNINDENT .INDENT 0.0 .TP .B validators.hashes.md5(value: str, /) @@ -1751,46 +2111,65 @@ If \fIvalue\fP is an invalid hostname. .sp > \fINew in version 0.21.0\fP\&. .UNINDENT -.SS i18n .INDENT 0.0 .TP -.B validators.i18n.es_cif(value: str, /) -Validate a Spanish CIF. -.sp -Each company in Spain prior to 2008 had a distinct CIF and has been -discontinued. For more information see [wikipedia.org/cif][1]. -.sp -The new replacement is to use NIF for absolutely everything. The issue is -that there are \(dqtypes\(dq of NIFs now: company, person [citizen or resident] -all distinguished by the first character of the DOI. For this reason we -will continue to call CIFs NIFs, that are used for companies. -.sp -This validator is based on [generadordni.es][2]. -.sp -[1]: \fI\%https://es.wikipedia.org/wiki/C%C3%B3digo_de_identificaci%C3%B3n_fiscal\fP -[2]: \fI\%https://generadordni.es/\fP +.B validators.hostname.hostname(value: str, /, *, skip_ipv6_addr: bool = False, skip_ipv4_addr: bool = False, may_have_port: bool = True, maybe_simple: bool = True, rfc_1034: bool = False, rfc_2782: bool = False) +Return whether or not given value is a valid hostname. .sp Examples .sp .nf .ft C ->>> es_cif(\(aqB25162520\(aq) +>>> hostname(\(dqubuntu\-pc:443\(dq) # Output: True ->>> es_cif(\(aqB25162529\(aq) -# Output: ValidationError(func=es_cif, args=...) +>>> hostname(\(dqthis\-pc\(dq) +# Output: True +>>> hostname(\(dqxn\-\-\-\-gtbspbbmkef.xn\-\-p1ai:65535\(dq) +# Output: True +>>> hostname(\(dq_example.com\(dq) +# Output: True +>>> hostname(\(dq123.5.77.88:31000\(dq) +# Output: True +>>> hostname(\(dq12.12.12.12\(dq) +# Output: True +>>> hostname(\(dq[::1]:22\(dq) +# Output: True +>>> hostname(\(dqdead:beef:0:0:0:0000:42:1\(dq) +# Output: True +>>> hostname(\(dq[0:0:0:0:0:ffff:1.2.3.4]:\-65538\(dq) +# Output: ValidationError(func=hostname, ...) +>>> hostname(\(dq[0:&:b:c:@:e:f::]:9999\(dq) +# Output: ValidationError(func=hostname, ...) .ft P .fi .INDENT 7.0 .TP .B Parameters -\fBvalue\fP \-\- DOI string which is to be validated. +.INDENT 7.0 +.IP \(bu 2 +\fBvalue\fP \-\- Hostname string to validate. +.IP \(bu 2 +\fBskip_ipv6_addr\fP \-\- When hostname string cannot be an IPv6 address. +.IP \(bu 2 +\fBskip_ipv4_addr\fP \-\- When hostname string cannot be an IPv4 address. +.IP \(bu 2 +\fBmay_have_port\fP \-\- Hostname string may contain port number. +.IP \(bu 2 +\fBmaybe_simple\fP \-\- Hostname string maybe only hyphens and alpha\-numerals. +.IP \(bu 2 +\fBrfc_1034\fP \-\- Allow trailing dot in domain/host name. +Ref: [RFC 1034](\fI\%https://www.rfc\-editor.org/rfc/rfc1034\fP). +.IP \(bu 2 +\fBrfc_2782\fP \-\- Domain/Host name is of type service record. +Ref: [RFC 2782](\fI\%https://www.rfc\-editor.org/rfc/rfc2782\fP). +.UNINDENT .TP .B Returns -If \fIvalue\fP is a valid DOI string. +If \fIvalue\fP is a valid hostname. (ValidationError): .INDENT 7.0 .INDENT 3.5 -If \fIvalue\fP is an invalid DOI string. +If \fIvalue\fP is an invalid hostname. .UNINDENT .UNINDENT @@ -1799,41 +2178,44 @@ If \fIvalue\fP is an invalid DOI string. (Literal[True]) .UNINDENT .sp -> \fINew in version 0.13.0\fP\&. +> \fINew in version 0.21.0\fP\&. .UNINDENT +.SS i18n .INDENT 0.0 .TP -.B validators.i18n.es_doi(value: str, /) -Validate a Spanish DOI. +.B validators.i18n.fr_ssn(value: str) +Validate a french Social Security Number. .sp -A DOI in spain is all NIF / CIF / NIE / DNI \-\- a digital ID. -For more information see [wikipedia.org/doi][1]. This validator -is based on [generadordni.es][2]. +Each french citizen has a distinct Social Security Number. +For more information see [French Social Security Number][1] (sadly unavailable in english). .sp -[1]: \fI\%https://es.wikipedia.org/wiki/Identificador_de_objeto_digital\fP -[2]: \fI\%https://generadordni.es/\fP +[1]: \fI\%https://fr.wikipedia.org/wiki/Num%C3%A9ro_de_s%C3%A9curit%C3%A9_sociale_en_France\fP .sp Examples .sp .nf .ft C ->>> es_doi(\(aqX0095892M\(aq) +>>> fr_ssn(\(aq1 84 12 76 451 089 46\(aq) # Output: True ->>> es_doi(\(aqX0095892X\(aq) -# Output: ValidationError(func=es_doi, args=...) +>>> fr_ssn(\(aq1 84 12 76 451 089\(aq) # control key is optional +# Output: True +>>> fr_ssn(\(aq3 84 12 76 451 089 46\(aq) # wrong gender number +# Output: ValidationError(func=fr_ssn, args=...) +>>> fr_ssn(\(aq1 84 12 76 451 089 47\(aq) # wrong control key +# Output: ValidationError(func=fr_ssn, args=...) .ft P .fi .INDENT 7.0 .TP .B Parameters -\fBvalue\fP \-\- DOI string which is to be validated. +\fBvalue\fP \-\- French Social Security Number string to validate. .TP .B Returns -If \fIvalue\fP is a valid DOI string. +If \fIvalue\fP is a valid french Social Security Number. (ValidationError): .INDENT 7.0 .INDENT 3.5 -If \fIvalue\fP is an invalid DOI string. +If \fIvalue\fP is an invalid french Social Security Number. .UNINDENT .UNINDENT @@ -1842,11 +2224,103 @@ If \fIvalue\fP is an invalid DOI string. (Literal[True]) .UNINDENT .sp -> \fINew in version 0.13.0\fP\&. +> \fINew in version 0.23.0\fP\&. .UNINDENT .INDENT 0.0 .TP -.B validators.i18n.es_nie(value: str, /) +.B validators.i18n.es_cif(value: str, /) +Validate a Spanish CIF. +.sp +Each company in Spain prior to 2008 had a distinct CIF and has been +discontinued. For more information see [wikipedia.org/cif][1]. +.sp +The new replacement is to use NIF for absolutely everything. The issue is +that there are \(dqtypes\(dq of NIFs now: company, person [citizen or resident] +all distinguished by the first character of the DOI. For this reason we +will continue to call CIFs NIFs, that are used for companies. +.sp +This validator is based on [generadordni.es][2]. +.sp +[1]: \fI\%https://es.wikipedia.org/wiki/C%C3%B3digo_de_identificaci%C3%B3n_fiscal\fP +[2]: \fI\%https://generadordni.es/\fP +.sp +Examples +.sp +.nf +.ft C +>>> es_cif(\(aqB25162520\(aq) +# Output: True +>>> es_cif(\(aqB25162529\(aq) +# Output: ValidationError(func=es_cif, args=...) +.ft P +.fi +.INDENT 7.0 +.TP +.B Parameters +\fBvalue\fP \-\- DOI string which is to be validated. +.TP +.B Returns +If \fIvalue\fP is a valid DOI string. +(ValidationError): +.INDENT 7.0 +.INDENT 3.5 +If \fIvalue\fP is an invalid DOI string. +.UNINDENT +.UNINDENT + +.TP +.B Return type +(Literal[True]) +.UNINDENT +.sp +> \fINew in version 0.13.0\fP\&. +.UNINDENT +.INDENT 0.0 +.TP +.B validators.i18n.es_doi(value: str, /) +Validate a Spanish DOI. +.sp +A DOI in spain is all NIF / CIF / NIE / DNI \-\- a digital ID. +For more information see [wikipedia.org/doi][1]. This validator +is based on [generadordni.es][2]. +.sp +[1]: \fI\%https://es.wikipedia.org/wiki/Identificador_de_objeto_digital\fP +[2]: \fI\%https://generadordni.es/\fP +.sp +Examples +.sp +.nf +.ft C +>>> es_doi(\(aqX0095892M\(aq) +# Output: True +>>> es_doi(\(aqX0095892X\(aq) +# Output: ValidationError(func=es_doi, args=...) +.ft P +.fi +.INDENT 7.0 +.TP +.B Parameters +\fBvalue\fP \-\- DOI string which is to be validated. +.TP +.B Returns +If \fIvalue\fP is a valid DOI string. +(ValidationError): +.INDENT 7.0 +.INDENT 3.5 +If \fIvalue\fP is an invalid DOI string. +.UNINDENT +.UNINDENT + +.TP +.B Return type +(Literal[True]) +.UNINDENT +.sp +> \fINew in version 0.13.0\fP\&. +.UNINDENT +.INDENT 0.0 +.TP +.B validators.i18n.es_nie(value: str, /) Validate a Spanish NIE. .sp The NIE is a tax identification number in Spain, known in Spanish @@ -2570,6 +3044,42 @@ If \fIvalue\fP is an invalid IBAN code. .UNINDENT .UNINDENT +.TP +.B Return type +(Literal[True]) +.UNINDENT +.sp +> \fINew in version 0.8.0\fP +.UNINDENT +.INDENT 0.0 +.TP +.B validators.iban.iban(value: str, /) +Return whether or not given value is a valid IBAN code. +.sp +Examples +.sp +.nf +.ft C +>>> iban(\(aqDE29100500001061045672\(aq) +# Output: True +>>> iban(\(aq123456\(aq) +# Output: ValidationError(func=iban, ...) +.ft P +.fi +.INDENT 7.0 +.TP +.B Parameters +\fBvalue\fP \-\- IBAN string to validate. +.TP +.B Returns +If \fIvalue\fP is a valid IBAN code. +(ValidationError): +.INDENT 7.0 +.INDENT 3.5 +If \fIvalue\fP is an invalid IBAN code. +.UNINDENT +.UNINDENT + .TP .B Return type (Literal[True]) @@ -2580,6 +3090,77 @@ If \fIvalue\fP is an invalid IBAN code. .SS ip_address .INDENT 0.0 .TP +.B validators.ip_address.ipv6(value: str, /, *, cidr: bool = True, strict: bool = False, host_bit: bool = True) +Returns if a given value is a valid IPv6 address. +.sp +Including IPv4\-mapped IPv6 addresses. The initial version of ipv6 validator +was inspired from [WTForms IPAddress validator][1]. +.sp +[1]: \fI\%https://github.com/wtforms/wtforms/blob/master/src/wtforms/validators.py\fP +.sp +Examples +.sp +.nf +.ft C +>>> ipv6(\(aq::ffff:192.0.2.128\(aq) +# Output: True +>>> ipv6(\(aq::1/128\(aq) +# Output: True +>>> ipv6(\(aqabc.0.0.1\(aq) +# Output: ValidationError(func=ipv6, args={\(aqvalue\(aq: \(aqabc.0.0.1\(aq}) +.ft P +.fi +.INDENT 7.0 +.TP +.B Parameters +.INDENT 7.0 +.IP \(bu 2 +\fBvalue\fP \-\- IP address string to validate. +.IP \(bu 2 +\fBcidr\fP \-\- IP address string may contain CIDR annotation +.IP \(bu 2 +\fBstrict\fP \-\- IP address string is strictly in CIDR notation +.IP \(bu 2 +\fBhost_bit\fP \-\- If \fIFalse\fP and host bits (along with network bits) _are_ set in the supplied +address, this function raises a validation error. ref [IPv6Network][2]. +[2]: \fI\%https://docs.python.org/3/library/ipaddress.html#ipaddress.IPv6Network\fP +.UNINDENT +.TP +.B Returns +If \fIvalue\fP is a valid IPv6 address. +(ValidationError): +.INDENT 7.0 +.INDENT 3.5 +If \fIvalue\fP is an invalid IPv6 address. +.UNINDENT +.UNINDENT + +.TP +.B Return type +(Literal[True]) +.UNINDENT +.sp +\fBNOTE:\fP +.INDENT 7.0 +.INDENT 3.5 +.INDENT 0.0 +.IP \(bu 2 +.INDENT 2.0 +.TP +.B \fIIn version 0.14.0\fP: +.INDENT 7.0 +.IP \(bu 2 +Add supports for CIDR notation +.UNINDENT +.UNINDENT +.UNINDENT +.UNINDENT +.UNINDENT +.sp +> \fINew in version 0.2.0\fP +.UNINDENT +.INDENT 0.0 +.TP .B validators.ip_address.ipv4(value: str, /, *, cidr: bool = True, strict: bool = False, host_bit: bool = True) Returns whether a given value is a valid IPv4 address. .sp @@ -2867,7 +3448,7 @@ Add supports for CIDR notation .SS length .INDENT 0.0 .TP -.B validators.length.length(value: str, /, *, min_val: int = 0, max_val: int = 0) +.B validators.length.length(value: str, /, *, min_val: int | None = None, max_val: int | None = None) Return whether or not the length of given string is within a specified range. .sp Examples @@ -2908,13 +3489,14 @@ If \fIlen(value)\fP is not in between the given conditions. .TP .B Return type (Literal[True]) +.TP +.B Raises +\fB(\fP\fBValueError\fP\fB)\fP \-\- If either \fImin_val\fP or \fImax_val\fP is negative. .UNINDENT -.sp -> \fINew in version 0.2.0\fP\&. .UNINDENT .INDENT 0.0 .TP -.B validators.length.length(value: str, /, *, min_val: int = 0, max_val: int = 0) +.B validators.length.length(value: str, /, *, min_val: int | None = None, max_val: int | None = None) Return whether or not the length of given string is within a specified range. .sp Examples @@ -2955,9 +3537,58 @@ If \fIlen(value)\fP is not in between the given conditions. .TP .B Return type (Literal[True]) +.TP +.B Raises +\fB(\fP\fBValueError\fP\fB)\fP \-\- If either \fImin_val\fP or \fImax_val\fP is negative. .UNINDENT +.UNINDENT +.INDENT 0.0 +.TP +.B validators.length.length(value: str, /, *, min_val: int | None = None, max_val: int | None = None) +Return whether or not the length of given string is within a specified range. .sp -> \fINew in version 0.2.0\fP\&. +Examples +.sp +.nf +.ft C +>>> length(\(aqsomething\(aq, min_val=2) +# Output: True +>>> length(\(aqsomething\(aq, min_val=9, max_val=9) +# Output: True +>>> length(\(aqsomething\(aq, max_val=5) +# Output: ValidationError(func=length, ...) +.ft P +.fi +.INDENT 7.0 +.TP +.B Parameters +.INDENT 7.0 +.IP \(bu 2 +\fBvalue\fP \-\- The string to validate. +.IP \(bu 2 +\fBmin_val\fP \-\- The minimum required length of the string. If not provided, +minimum length will not be checked. +.IP \(bu 2 +\fBmax_val\fP \-\- The maximum length of the string. If not provided, +maximum length will not be checked. +.UNINDENT +.TP +.B Returns +If \fIlen(value)\fP is in between the given conditions. +(ValidationError): +.INDENT 7.0 +.INDENT 3.5 +If \fIlen(value)\fP is not in between the given conditions. +.UNINDENT +.UNINDENT + +.TP +.B Return type +(Literal[True]) +.TP +.B Raises +\fB(\fP\fBValueError\fP\fB)\fP \-\- If either \fImin_val\fP or \fImax_val\fP is negative. +.UNINDENT .UNINDENT .SS mac_address .INDENT 0.0 @@ -3040,12 +3671,91 @@ If \fIvalue\fP is an invalid MAC address. .sp > \fINew in version 0.2.0\fP\&. .UNINDENT -.SS slug .INDENT 0.0 .TP -.B validators.slug.slug(value: str, /) -Validate whether or not given value is valid slug. -.sp +.B validators.mac_address.mac_address(value: str, /) +Return whether or not given value is a valid MAC address. +.sp +This validator is based on [WTForms MacAddress validator][1]. +.sp +[1]: \fI\%https://github.com/wtforms/wtforms/blob/master/src/wtforms/validators.py#L482\fP +.sp +Examples +.sp +.nf +.ft C +>>> mac_address(\(aq01:23:45:67:ab:CD\(aq) +# Output: True +>>> mac_address(\(aq00:00:00:00:00\(aq) +# Output: ValidationError(func=mac_address, args={\(aqvalue\(aq: \(aq00:00:00:00:00\(aq}) +.ft P +.fi +.INDENT 7.0 +.TP +.B Parameters +\fBvalue\fP \-\- MAC address string to validate. +.TP +.B Returns +If \fIvalue\fP is a valid MAC address. +(ValidationError): +.INDENT 7.0 +.INDENT 3.5 +If \fIvalue\fP is an invalid MAC address. +.UNINDENT +.UNINDENT + +.TP +.B Return type +(Literal[True]) +.UNINDENT +.sp +> \fINew in version 0.2.0\fP\&. +.UNINDENT +.SS slug +.INDENT 0.0 +.TP +.B validators.slug.slug(value: str, /) +Validate whether or not given value is valid slug. +.sp +Valid slug can contain only lowercase alphanumeric characters and hyphens. +It starts and ends with these lowercase alphanumeric characters. +.sp +Examples +.sp +.nf +.ft C +>>> slug(\(aqmy\-slug\-2134\(aq) +# Output: True +>>> slug(\(aqmy.slug\(aq) +# Output: ValidationError(func=slug, args={\(aqvalue\(aq: \(aqmy.slug\(aq}) +.ft P +.fi +.INDENT 7.0 +.TP +.B Parameters +\fBvalue\fP \-\- Slug string to validate. +.TP +.B Returns +If \fIvalue\fP is a valid slug. +(ValidationError): +.INDENT 7.0 +.INDENT 3.5 +If \fIvalue\fP is an invalid slug. +.UNINDENT +.UNINDENT + +.TP +.B Return type +(Literal[True]) +.UNINDENT +.sp +> \fINew in version 0.6.0\fP\&. +.UNINDENT +.INDENT 0.0 +.TP +.B validators.slug.slug(value: str, /) +Validate whether or not given value is valid slug. +.sp Valid slug can contain only lowercase alphanumeric characters and hyphens. It starts and ends with these lowercase alphanumeric characters. .sp @@ -3329,6 +4039,137 @@ If \fIvalue\fP is an invalid slug. .UNINDENT .UNINDENT +.TP +.B Return type +(Literal[True]) +.UNINDENT +.sp +\fBNOTE:\fP +.INDENT 7.0 +.INDENT 3.5 +.INDENT 0.0 +.IP \(bu 2 +.INDENT 2.0 +.TP +.B \fIIn version 0.11.3\fP: +.INDENT 7.0 +.IP \(bu 2 +Added support for URLs containing localhost. +.UNINDENT +.UNINDENT +.IP \(bu 2 +.INDENT 2.0 +.TP +.B \fIIn version 0.11.0\fP: +.INDENT 7.0 +.IP \(bu 2 +Made the regular expression case insensitive. +.UNINDENT +.UNINDENT +.IP \(bu 2 +.INDENT 2.0 +.TP +.B \fIIn version 0.10.3\fP: +.INDENT 7.0 +.IP \(bu 2 +Added a \fIpublic\fP parameter. +.UNINDENT +.UNINDENT +.IP \(bu 2 +.INDENT 2.0 +.TP +.B \fIIn version 0.10.2\fP: +.INDENT 7.0 +.IP \(bu 2 +Added support for various exotic URLs. +.IP \(bu 2 +Fixed various false positives. +.UNINDENT +.UNINDENT +.UNINDENT +.UNINDENT +.UNINDENT +.sp +> \fINew in version 0.2.0\fP\&. +.UNINDENT +.INDENT 0.0 +.TP +.B validators.url.url(value: str, /, *, skip_ipv6_addr: bool = False, skip_ipv4_addr: bool = False, may_have_port: bool = True, simple_host: bool = False, strict_query: bool = True, rfc_1034: bool = False, rfc_2782: bool = False) +Return whether or not given value is a valid URL. +.sp +This validator was inspired from [URL validator of dperini][1]. +The following diagram is from [urlly][2]. +.INDENT 7.0 +.INDENT 3.5 +.INDENT 0.0 +.INDENT 3.5 +foo://admin:hunter1@example.com:8042/over/there?name=ferret#nose +_/ ___/ _____/ _________/ __/_________/ _________/ __/ +.INDENT 0.0 +.INDENT 3.5 +.nf +| | | | | | | +.fi +.sp +.UNINDENT +.UNINDENT +.UNINDENT +.UNINDENT +.sp +scheme username password hostname port path query fragment +.UNINDENT +.UNINDENT +.sp +[1]: \fI\%https://gist.github.com/dperini/729294\fP +[2]: \fI\%https://github.com/treeform/urlly\fP +.sp +Examples +.sp +.nf +.ft C +>>> url(\(aqhttp://duck.com\(aq) +# Output: True +>>> url(\(aqftp://foobar.dk\(aq) +# Output: True +>>> url(\(aqhttp://10.0.0.1\(aq) +# Output: True +>>> url(\(aqhttp://example.com/\(dq>user@example.com\(aq) +# Output: ValidationError(func=url, ...) +.ft P +.fi +.INDENT 7.0 +.TP +.B Parameters +.INDENT 7.0 +.IP \(bu 2 +\fBvalue\fP \-\- URL string to validate. +.IP \(bu 2 +\fBskip_ipv6_addr\fP \-\- When URL string cannot contain an IPv6 address. +.IP \(bu 2 +\fBskip_ipv4_addr\fP \-\- When URL string cannot contain an IPv4 address. +.IP \(bu 2 +\fBmay_have_port\fP \-\- URL string may contain port number. +.IP \(bu 2 +\fBsimple_host\fP \-\- URL string maybe only hyphens and alpha\-numerals. +.IP \(bu 2 +\fBstrict_query\fP \-\- Fail validation on query string parsing error. +.IP \(bu 2 +\fBrfc_1034\fP \-\- Allow trailing dot in domain/host name. +Ref: [RFC 1034](\fI\%https://www.rfc\-editor.org/rfc/rfc1034\fP). +.IP \(bu 2 +\fBrfc_2782\fP \-\- Domain/Host name is of type service record. +Ref: [RFC 2782](\fI\%https://www.rfc\-editor.org/rfc/rfc2782\fP). +.UNINDENT +.TP +.B Returns +If \fIvalue\fP is a valid slug. +(ValidationError): +.INDENT 7.0 +.INDENT 3.5 +If \fIvalue\fP is an invalid slug. +.UNINDENT +.UNINDENT + .TP .B Return type (Literal[True]) @@ -3385,6 +4226,42 @@ Fixed various false positives. .SS utils .INDENT 0.0 .TP +.B validators.utils.validator(func: Callable[[\&...], Any]) +A decorator that makes given function validator. +.sp +Whenever the given \fIfunc\fP returns \fIFalse\fP this +decorator returns \fIValidationError\fP object. +.sp +Examples +.sp +.nf +.ft C +>>> @validator +\&... def even(value): +\&... return not (value % 2) +>>> even(4) +# Output: True +>>> even(5) +# Output: ValidationError(func=even, args={\(aqvalue\(aq: 5}) +.ft P +.fi +.INDENT 7.0 +.TP +.B Parameters +\fBfunc\fP \-\- Function which is to be decorated. +.TP +.B Returns +A decorator which returns either \fIValidationError\fP +or \fILiteral[True]\fP\&. +.TP +.B Return type +(Callable[\&..., ValidationError | Literal[True]]) +.UNINDENT +.sp +> \fINew in version 2013.10.21\fP\&. +.UNINDENT +.INDENT 0.0 +.TP .B validators.utils.ValidationError(function: Callable[[\&...], Any], arg_dict: Dict[str, Any], message: str = \(aq\(aq) Exception class when validation failure occurs. .UNINDENT @@ -3539,6 +4416,46 @@ If \fIvalue\fP is an invalid UUID. .UNINDENT .UNINDENT +.TP +.B Return type +(Literal[True]) +.UNINDENT +.sp +> \fINew in version 0.2.0\fP\&. +.UNINDENT +.INDENT 0.0 +.TP +.B validators.uuid.uuid(value: str | UUID, /) +Return whether or not given value is a valid UUID\-v4 string. +.sp +This validator is based on [WTForms UUID validator][1]. +.sp +[1]: \fI\%https://github.com/wtforms/wtforms/blob/master/src/wtforms/validators.py#L539\fP +.sp +Examples +.sp +.nf +.ft C +>>> uuid(\(aq2bc1c94f\-0deb\-43e9\-92a1\-4775189ec9f8\(aq) +# Output: True +>>> uuid(\(aq2bc1c94f 0deb\-43e9\-92a1\-4775189ec9f8\(aq) +# Output: ValidationError(func=uuid, ...) +.ft P +.fi +.INDENT 7.0 +.TP +.B Parameters +\fBvalue\fP \-\- UUID string or object to validate. +.TP +.B Returns +If \fIvalue\fP is a valid UUID. +(ValidationError): +.INDENT 7.0 +.INDENT 3.5 +If \fIvalue\fP is an invalid UUID. +.UNINDENT +.UNINDENT + .TP .B Return type (Literal[True])