Last active
December 27, 2019 19:22
-
-
Save jorgecrodrigues/570b8ab93e819799dd67fe00682b259a to your computer and use it in GitHub Desktop.
Validação de CPF usando javascript
This file contains hidden or 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 cpf(value) { | |
var numbers, isValid; | |
// Retorna falso se o valor não for do tipo string. | |
if (!typeof value === 'string') return false; | |
// Remove todos os caracteres que não são numéricos. | |
numbers = value.replace(/[^0-9]/g, ''); | |
// Verifica se não existem valores repetidos. Ex: 111.111.111-11 | |
if (numbers.match(/(\d)\1{10}/)) return false; | |
for (i = 9; i < 11; i++) { | |
for (d = 0, c = 0; c < i; c++) { | |
d += numbers[c] * ((i + 1) - c); | |
} | |
d = ((10 * d) % 11) % 10; | |
isValid = (numbers[c] == d); | |
} | |
return isValid; | |
} | |
function cnpj(value) { | |
var numbers, isValid, rest; | |
// Retorna falso se o valor não for do tipo string. | |
if (!typeof value === 'string') return false; | |
// Remove todos os caracteres que não são numéricos. | |
numbers = value.replace(/[^0-9]/g, ''); | |
// Verifica se não existem valores repetidos. Ex: 111.111.111-11 | |
if (numbers.match(/(\d)\1{13}/)) return false; | |
for (i = 0, j = 5, sum = 0; i < 12; i++) { | |
sum += numbers[i] * j; | |
// 5,4,3,2,9,8,7,6,5,4,3,2 | |
j = (j === 2) ? 9 : j - 1; | |
} | |
rest = sum % 11; | |
isValid = numbers[12] == (rest < 2 ? 0 : 11 - rest); | |
// Faz a validação do segundo dígito verificador. | |
for (i = 0, j = 6, sum = 0; i < 13; i++) { | |
sum += numbers[i] * j; | |
// 6,5,4,3,2,9,8,7,6,5,4,3,2 | |
j = (j === 2) ? 9 : j - 1; | |
} | |
rest = sum % 11; | |
isValid = isValid && (numbers[13] == (rest < 2 ? 0 : 11 - rest)); | |
return isValid; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment