Skip to content

Instantly share code, notes, and snippets.

@mathifonseca
Last active January 2, 2024 18:19
Show Gist options
  • Save mathifonseca/2234b4e4e52eaa78bd512e8c9c77b912 to your computer and use it in GitHub Desktop.
Save mathifonseca/2234b4e4e52eaa78bd512e8c9c77b912 to your computer and use it in GitHub Desktop.
Brazilian mobile phone validator
/*
Anatel Documentation -> http://www.anatel.gov.br/Portal/exibirPortalPaginaEspecial.do?org.apache.struts.taglib.html.TOKEN=9594e1d11fbc996d52bda44e608bb744&codItemCanal=1794&pastaSelecionada=2984
TL;DR:
Before 2012-07-29, Brazilian mobile phones where 10 digits long, 2 of them being an area code. e.g.: 11 2222-3333
From then on, they are slowly adding a ninth digit between the area code and the user's number, like this: 11 9 2222-3333
This process will end on 2016-12-31, so if you are reading this after that date, ignore the first method and use the second one.
*/
boolean isValidBrazilianMobilePhoneBefore20161231(String phone) {
//remove all non numeric chars
phone = phone.replaceAll(/\D+/,'')
//remove trailing zero if present
if (phone.startsWith('0')) phone = phone[1..-1]
//phone should be exactly 10 or 11 numeric digits
if (!phone.isLong() || !(phone.size() in [10, 11])) return false
//check if DDD is valid
def notListed = [20,23,25,26,29,30,36,39,40,50,52,56,57,58,59,60,70,72,76,78,80,90]
int ddd = phone[0..1].toInteger()
if (ddd < 11 || ddd in notListed) return false
//check if number should be 8 or 9 digits
def num = phone[2..-1]
//if 9 digits, first one should be 9
if (num.size() == 9 && !num.startsWith('9')) return false
//starting from 2016-12-31, all phones should start with 9 and be 9 digits long
//TODO refactor this code after that date
def eightDigits = new Date().before(Date.parse('yyyy-MM-dd', '2016-12-31')) ?
[41,42,43,44,45,46,47,48,49,51,53,54,55,61,62,64,63,65,66,67,68,69] : []
if (ddd in eightDigits) {
return num.size() == 8
} else {
return num.size() == 9 && num.startsWith('9')
}
}
public boolean isValidBrazilianMobilePhone(String phone) {
//remove all non numeric chars
phone = phone.replaceAll(/\D+/,'')
//remove trailing zero if present
if (phone.startsWith('0')) phone = phone[1..-1]
//phone should be exactly 11 numeric digits
if (!phone.isLong() || phone.size() != 11) return false
//check if DDD is valid
def notListed = [20,23,25,26,29,30,36,39,40,50,52,56,57,58,59,60,70,72,76,78,80,90]
int ddd = phone[0..1].toInteger()
if (ddd < 11 || ddd in notListed) return false
//number is 9 digits long and starts with 9
return phone[2..-1].size() == 9 && phone[2..-1].startsWith('9')
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment