Navigation Menu

Skip to content

Instantly share code, notes, and snippets.

@cheldernunes
Created October 12, 2018 00:20
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save cheldernunes/49b2f81add94e06712607473d67cff32 to your computer and use it in GitHub Desktop.
Save cheldernunes/49b2f81add94e06712607473d67cff32 to your computer and use it in GitHub Desktop.
Django RegexValidator for phone numbers with ddd+number(8 or 9) digits
# brazil's code areas
# http://www.anatel.gov.br/setorregulado/codigos-nacionais/codigos-nacionais
# http://www.anatel.gov.br/legislacao/resolucoes/16-2001/383-resolucao-263
phone_validator = RegexValidator(regex=r'^(1[1-9]|2[1-2,4,7,8]|3[1-5]|3[7-8]|4[1-9]'
r'|5[1,3-5]|6[1-9]|7[1,3,4,5,7,9]'
r'|8[1-9]|9[1-9]){1}[0-9]{8,9}$',
message="Phone number must be entered in the format '99000000000'. "
"where 99(2 digits) is a brazil code area, and 000000000 is a number phone "
"with 8 or 9 digits.")
DDDS_BRAZIL = {
"11": "SP",
"12": "SP",
"13": "SP",
"14": "SP",
"15": "SP",
"16": "SP",
"17": "SP",
"18": "SP",
"19": "SP",
"21": "RJ",
"22": "RJ",
"24": "RJ",
"27": "ES",
"28": "ES",
"31": "MG",
"32": "MG",
"33": "MG",
"34": "MG",
"35": "MG",
"37": "MG",
"38": "MG",
"41": "PR",
"42": "PR",
"43": "PR",
"44": "PR",
"45": "PR",
"46": "PR",
"47": "SC",
"48": "SC",
"49": "SC",
"51": "RS",
"53": "RS",
"54": "RS",
"55": "RS",
"61": "DF",
"62": "GO",
"63": "TO",
"64": "GO",
"65": "MT",
"66": "MT",
"67": "MS",
"68": "AC",
"69": "RO",
"71": "BA",
"73": "BA",
"74": "BA",
"75": "BA",
"77": "BA",
"79": "SE",
"81": "PE",
"82": "AL",
"83": "PB",
"84": "RN",
"85": "CE",
"86": "PI",
"87": "PE",
"88": "CE",
"89": "PI",
"91": "PA",
"92": "AM",
"93": "PA",
"94": "PA",
"95": "RR",
"96": "AP",
"97": "AM",
"98": "MA",
"99": "MA"
}
def test_size_number():
with pytest.raises(ValidationError):
# ddd + big number
phone_validator.__call__('11999999999999')
# ddd + tiny number
phone_validator.__call__('21999999')
# ddd + eight number
phone_validator.__call__('2199999999')
# ddd + nine number
phone_validator.__call__('21999999999')
def test_nice_ddd_number():
for ddd in DDDS_BRAZIL:
assert phone_validator.__call__('{}999999999'.format(ddd)) is None
def test_wrong_ddd_number():
wrongs_ddds = [val for val in range(10, 100) if str(val) not in [ddd for ddd in DDDS_BRAZIL]]
with pytest.raises(ValidationError):
for ddds in wrongs_ddds:
phone_validator.__call__('{}999999999999'.format(ddds))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment