Skip to content

Instantly share code, notes, and snippets.

@wellserrano
Last active March 24, 2023 14:02
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save wellserrano/ff53dbab2efad7b7c810b9478dc57594 to your computer and use it in GitHub Desktop.
Save wellserrano/ff53dbab2efad7b7c810b9478dc57594 to your computer and use it in GitHub Desktop.
export function validateCpf(cpf: string) {
cpf = cpf.replace(/[^\d]+/g,'')
if (
cpf.length !== 11 ||
cpf === '' ||
cpf === "00000000000" ||
cpf === "11111111111" ||
cpf === "22222222222" ||
cpf === "33333333333" ||
cpf === "44444444444" ||
cpf === "55555555555" ||
cpf === "66666666666" ||
cpf === "77777777777" ||
cpf === "88888888888" ||
cpf === "99999999999"
) {
return false;
}
let add = 0;
for (let i=0; i < 9; i++) {
add += parseInt(cpf.charAt(i)) * (10 - i);
}
let rev = 11 - (add % 11);
if (rev == 10 || rev == 11) rev = 0;
if (rev != parseInt(cpf.charAt(9))) return false;
add = 0;
for (let i = 0; i < 10; i ++) {
add += parseInt(cpf.charAt(i)) * (11 - i);
}
rev = 11 - (add % 11);
if (rev == 10 || rev == 11) rev = 0;
if (rev != parseInt(cpf.charAt(10))) return false
return true;
}
@wellserrano
Copy link
Author

wellserrano commented Mar 24, 2023

Regex for formatting the input to the CPF pattern XXX.XXX.XXX-XX

const formatCpf = /^\d{3}\.\d{3}\.\d{3}-\d{2}$/

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment