1
I have the following code of a form that when leaving the CPF field is made the validation of the CPF. I would like if the test is unsuccessful to include the "has-error" class in the div where the input is located and if it is successful to add the "has-Success" class. As I have several Ivs with the class "form-group" I tried to use the parents()
but it didn’t work.
function validaCPF2(cpf_principal_condutor) {
if (!testCPF2(cpf_principal_condutor)) {
$('#errocpf2').show();
$(this).parents('.form-group').removeClass('has-success');
$(this).parents('.form-group').addClass('has-error');
document.getElementById("cpf_principal_condutor").focus();
return false;
} else {
$('#errocpf2').hide();
$(this).parents('.form-group').removeClass('has-error');
$(this).parents('.form-group').addClass('has-success');
return true;
}
};
function testCPF2() {
var strCPF = $("#cpf_principal_condutor").val().replace(".","").replace(".","").replace('-',"").replace("_","");
var Soma;
var Resto;
Soma = 0;
if (strCPF === "00000000000") return false;
if (strCPF === "11111111111") return false;
if (strCPF === "22222222222") return false;
if (strCPF === "33333333333") return false;
if (strCPF === "44444444444") return false;
if (strCPF === "55555555555") return false;
if (strCPF === "66666666666") return false;
if (strCPF === "77777777777") return false;
if (strCPF === "88888888888") return false;
if (strCPF === "99999999999") return false;
for (i=1; i<=9; i++) Soma = Soma + parseInt(strCPF.substring(i-1, i)) * (11 - i);
Resto = (Soma * 10) % 11;
if ((Resto === 10) || (Resto === 11)) Resto = 0;
if (Resto !== parseInt(strCPF.substring(9, 10)) ) return false;
Soma = 0;
for (i = 1; i <= 10; i++) Soma = Soma + parseInt(strCPF.substring(i-1, i)) * (12 - i);
Resto = (Soma * 10) % 11;
if ((Resto === 10) || (Resto === 11)) Resto = 0;
if (Resto !== parseInt(strCPF.substring(10, 11) ) ) return false;
return true;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="form-group">
<label class="control-label">Nome completo do condutor principal do veículo: *</label>
<input id="nome_principal_condutor" name="nome_principal_condutor" placeholder=" " type="text" class="form-control" required>
</div>
<div class="form-group">
<label class="control-label">CPF do principal condutor *</label>
<input id="cpf_principal_condutor" name="cpf_principal_condutor" placeholder="123.456.789-00" onblur="validaCPF2();" type="text" class="form-control" required>
<small id="errocpf2" style="color: #a94442; display:none;" class="help-block">O CPF informado é inválido</small>
</div>
Perfect @Sam thanks so much for the help.
– Frederico Moreira
perfect uncle sam
– user60252
@Leocaracciolo was worth grandpa
– Sam