Skip to content

country_code

validators.country_code.country_code(value, /, *, iso_format='auto')

Validates given country code.

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

Examples:

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

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 /opt/hostedtoolcache/Python/3.11.7/x64/lib/python3.11/site-packages/validators/country_code.py
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
@validator
def country_code(value: str, /, *, iso_format: str = "auto"):
    """Validates given country code.

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

    [1]: https://www.iso.org/iso-3166-country-codes.html

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

    Args:
        value:
            Country code string to validate.
        iso_format:
            ISO format to be used. Available options are:
            `auto`, `alpha2`, `alpha3` and `numeric`.

    Returns:
        (Literal[True]):
            If `value` is a valid country code.
        (ValidationError):
            If `value` is an invalid country code.
    """
    if not value:
        return False

    if not (1 < len(value) < 4):
        return False

    if iso_format == "auto" and (iso_format := get_code_type(value)) == "invalid":
        return False

    if iso_format == "alpha2":
        return value in alpha_2
    if iso_format == "alpha3":
        return value in alpha_3
    return value in numeric if iso_format == "numeric" else False