Created
September 3, 2020 22:21
-
-
Save thiagoalvesfoz/60151321ef9305ba5ad24fe97f81df53 to your computer and use it in GitHub Desktop.
Mascara e Validador para CPF
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 cpfMask(value) { | |
return value | |
.replace(/\D/g, "") | |
.replace(/(\d{3})(\d)/, "$1.$2") | |
.replace(/(\d{3})(\d)/, "$1.$2") | |
.replace(/(\d{3})(\d{1,2})/, "$1-$2") | |
.replace(/(-\d{2})\d+?$/, "$1"); | |
}; | |
// EXEMPLO | |
// const mask = cpfMask("12345678912"); | |
// console.log(mask) | |
// SAÍDA: "123.456.789-12" | |
function validaCPF(value) { | |
if (typeof value !== "string") return false; | |
const cpf = value.replace(/[^\d]+/g, ""); //remove tudo exceto numeros | |
//testa os erros mais comuns | |
if ( | |
!cpf || | |
cpf.length !== 11 || | |
cpf == "00000000000" || | |
cpf == "11111111111" || | |
cpf == "22222222222" || | |
cpf == "33333333333" || | |
cpf == "44444444444" || | |
cpf == "55555555555" || | |
cpf == "66666666666" || | |
cpf == "77777777777" || | |
cpf == "88888888888" || | |
cpf == "99999999999" | |
) | |
return false; | |
let soma = 0; | |
let resto; | |
for (i = 1; i <= 9; i++) soma += parseInt(cpf.substring(i - 1, i)) * (11 - i); | |
resto = (soma * 10) % 11; | |
if (resto == 10 || resto == 11) resto = 0; | |
if (resto != parseInt(cpf.substring(9, 10))) return false; | |
soma = 0; | |
for (i = 1; i <= 10; i++) | |
soma += parseInt(cpf.substring(i - 1, i)) * (12 - i); | |
resto = (soma * 10) % 11; | |
if (resto == 10 || resto == 11) resto = 0; | |
if (resto != parseInt(cpf.substring(10, 11))) return false; | |
return true; | |
}; | |
// EXEMPLO | |
// if (validaCPF(cpfValue)) | |
// console.log("cpf válido"); | |
// else | |
// console.log("cpf inválido"); | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment