Last active
March 11, 2024 21:28
-
-
Save satinP/1b30195d11bc6a774bb64f1498400963 to your computer and use it in GitHub Desktop.
Máscara e Validador de Chave Pix Aleatória
This file contains 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
function maskPixRandomKey(value: string): string { | |
/** | |
* Filtra caracteres de 0 a 9 e de a a f, conforme os manuais: | |
* https://www.bcb.gov.br/content/estabilidadefinanceira/pix/Regulamento_Pix/X_ManualOperacionaldoDICT.pdf - Página 14` | |
* https://www.bcb.gov.br/content/estabilidadefinanceira/pix/API-DICT-2.0.1.html#tag/Key | |
*/ | |
const cleanValue = value.replace(/[^0-9a-f]/g, '').substring(0, 32) | |
if (cleanValue.length < 9) { | |
return cleanValue | |
} | |
if (cleanValue.length < 13) { | |
return cleanValue.replace(/^([0-9a-f]{8})([0-9a-f]+)/, '$1-$2') | |
} | |
if (cleanValue.length < 17) { | |
return cleanValue.replace( | |
/^([0-9a-f]{8})([0-9a-f]{4})([0-9a-f]+)/, | |
'$1-$2-$3' | |
) | |
} | |
if (cleanValue.length < 21) { | |
return cleanValue.replace( | |
/^([0-9a-f]{8})([0-9a-f]{4})([0-9a-f]{4})([0-9a-f]+)/, | |
'$1-$2-$3-$4' | |
) | |
} | |
return cleanValue.replace( | |
/^([0-9a-f]{8})([0-9a-f]{4})([0-9a-f]{4})([0-9a-f]{4})([0-9a-f]+)/, | |
'$1-$2-$3-$4-$5' | |
) | |
} | |
/** | |
* Valida chave de acordo com os manuais: | |
* https://www.bcb.gov.br/content/estabilidadefinanceira/pix/Regulamento_Pix/X_ManualOperacionaldoDICT.pdf - Página 14` | |
* https://www.bcb.gov.br/content/estabilidadefinanceira/pix/API-DICT-2.0.1.html#tag/Key | |
*/ | |
function isValidPixRandomKey (value: string): boolean { | |
return /[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/.test(value) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment