Skip to content

Instantly share code, notes, and snippets.

@satinP
Last active March 11, 2024 21:28
Show Gist options
  • Save satinP/1b30195d11bc6a774bb64f1498400963 to your computer and use it in GitHub Desktop.
Save satinP/1b30195d11bc6a774bb64f1498400963 to your computer and use it in GitHub Desktop.
Máscara e Validador de Chave Pix Aleatória
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