Validação de cpf Js
by Lucaskazama
HTML
<div class="flex">
<label>CPF:</label>
<input type="text" name="cpf" id="cpf" />
<button type="submit" class="enviar">Enviar</button>
<div id="result">CPF</div>
</div>
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/jquery.mask/1.14.0/jquery.mask.js"></script>
CSS
.flex {
display: table;
margin: 50px auto;
font-size: 20px;
}
#cpf {
border: 1px solid #dcdccd;
border-radius: 1rem;
background-color: white;
color: #222222;
padding: 4px;
font-size: 20px;
text-align: center;
}
.enviar {
border: 1px solid #dadada;
border-radius: 0.55rem;
background-color: #222222;
color: #dadada;
padding: 5px;
font-size: 16px;
}
#result {
margin-top: 20px;
display: none;
text-align: center;
}
JavaScript
$(document).ready(function() {
var maskCPF = "999.999.999-99";
$("#cpf").mask(maskCPF);
$(".enviar").click(function() {
var cpf = $("#cpf").val().replace(/[^\d]+/g, '');
function ValidaCPF(cpf) {
var Soma;
var Resto;
Soma = 0;
// Condições para remover cpf inválidos
if (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;
} else {
//Verifica o penultimo digito
for (i = 1; i <= 9; i++)
Soma = 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;
//Verifica o último digito
Soma = 0;
for (i = 1; i <= 10; i++)
Soma = 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;
}
$("#cpf").css('border-color', '#dcdccd');
return true;
}
if (ValidaCPF(cpf) == true) {
$('#result').html('CPF Validado!');
$("#result").show();
} else {
$("#cpf").css('border-color', 'red');
$('#result').html('CPF Inválido!');
$("#result").show();
}
});
});