Skip to content

Instantly share code, notes, and snippets.

@gruhh
Created January 26, 2023 00:53
Show Gist options
  • Save gruhh/ae9c7b26647b1a060f64f85ee9ab61a7 to your computer and use it in GitHub Desktop.
Save gruhh/ae9c7b26647b1a060f64f85ee9ab61a7 to your computer and use it in GitHub Desktop.
Validate Brazilian CPF number with Typescript
/*
* Validate Brazilian CPF number with Typescript
*
* @param {string} cpf - A string because can start with 0
*/
export const validateCpf: (cpf: string) => (boolean) = (cpf) => {
const _cpf = cpf.replace(/\D/g, '');
if (_cpf.length < 11) {
return false;
}
if (_cpf.split('').every(v => v == _cpf[0])) {
return false;
}
const d1 = (_cpf
.slice(0, 9)
.split('')
.reduce((a, v, i, arr) => a + parseInt(v) * (arr.length - i + 1), 0) * 10 % 11) % 10
=== parseInt(_cpf.slice(9, 10));
const d2 = (_cpf
.slice(0, 10)
.split('')
.reduce((a, v, i, arr) => a + parseInt(v) * (arr.length - i + 1), 0) * 10 % 11) % 10
=== parseInt(_cpf.slice(10, 11));
return d1 && d2;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment