Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Function to validate a CPF
function isValidCPF (cpf) {
let sum = 0,
remainder
cpf = cpf.toString().replace(/^\D+/g, '')
if (cpf.length != 11 || new Set(cpf).size === 1) return false
for (let i = 1; i <= 9; i++) sum = sum + parseInt(cpf.substring(i - 1, i)) * (11 - i)
remainder = (sum * 10) % 11
if (remainder == 10 || remainder == 11) remainder = 0
if (remainder != parseInt(cpf.substring(9, 10))) return false
sum = 0
for (let i = 1; i <= 10; i++) sum = sum + parseInt(cpf.substring(i - 1, i)) * (12 - i)
remainder = (sum * 10) % 11
if (remainder == 10 || remainder == 11) remainder = 0
if (remainder != parseInt(cpf.substring(10, 11))) return false
return true
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment