Created
September 17, 2021 17:21
-
-
Save Hfreitas/a2d440c26cef0c92b14567245757b3ce to your computer and use it in GitHub Desktop.
Valida e retorna parte de um numero telefonico
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// retorna se é um número internacional válido | |
const isValidInternationalNumber = (phoneNumber) => { | |
/* regex para validar se é um numero telefonico internacional válido, sinal de '+' opcional e sem extensão (exemplo: 'ramal xxx') | |
referência adaptada: https://stackoverflow.com/questions/16699007/regular-expression-to-match-standard-10-digit-phone-number | |
*/ | |
const phoneNumberRegex = | |
/^(\+\d{1,3}\s)?\(?\d{2,3}\)?[\s.-]?\d{3,5}[\s.-]?\d{4}$/g; | |
return phoneNumberRegex.test(phoneNumber); | |
}; | |
// extrai parte do numero a partir do final, após validar | |
const returnPhoneNumberSlice = (phoneNumber, sliceSize) => { | |
if (!isValidInternationalNumber(phoneNumber)) { | |
return ''; | |
} | |
// elimina espaços em branco | |
const trimmedPhoneNumber = phoneNumber.trim(); | |
// elimina todos os caracteres não numericos | |
const normalizePhoneNumber = trimmedPhoneNumber.replace(/\D/g, ''); | |
// retorna apenas parte do numero que necessita, a partir do final da string; | |
return normalizePhoneNumber.slice(-sliceSize); | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment