Solved

Brazilian CPF validator

  • 2 February 2024
  • 2 replies
  • 130 views

Badge

Hello, I'm trying to install a Brazilian CPF validator but I can't, the code doesn't work, could someone help me, follow the code:

 

<script>
    window.ub.form.customValidators.validarCPF = {
        isValid: function(value) {

            
    var cpf = value.replace(/[^\d]+/g, '');
    if (cpf == '') return false;
    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;
    add = 0;
    for (i = 0; i < 9; i++)
        add += parseInt(cpf.charAt(i)) * (10 - i);
    rev = 11 - (add % 11);
    if (rev == 10 || rev == 11)
        rev = 0;
    if (rev != parseInt(cpf.charAt(9)))
        return false;
    add = 0;
    for (i = 0; i < 10; i++)
        add += parseInt(cpf.charAt(i)) * (11 - i);
    rev = 11 - (add % 11);
    if (rev == 10 || rev == 11)
        rev = 0;
    if (rev != parseInt(cpf.charAt(10)))
        return false;
    return true;
},
      message: 'CPF INVÁLIDO',
   },
   window.ub.form.validationRules.cpf.validaCPF = true;   
      
</script>

icon

Best answer by Hristian 2 February 2024, 10:44

View original

2 replies

Userlevel 7
Badge +3

Hey @olitares,

This should do the trick: 
 

<script>
// Encapsulating the original CPF validation logic in a function
function validateCPF(cpfValue) {
var cpf = cpfValue.replace(/[^\d]+/g, '');
if (cpf == '' || cpf.length != 11) return false;
if (/^(.)\1+$/.test(cpf)) return false; // Simplified check for repeated numbers

var add = 0, rev;
for (var i = 0; i < 9; i++)
add += parseInt(cpf.charAt(i)) * (10 - i);
rev = 11 - (add % 11);
if (rev == 10 || rev == 11) rev = 0;
if (rev != parseInt(cpf.charAt(9))) return false;

add = 0;
for (var i = 0; i < 10; i++)
add += parseInt(cpf.charAt(i)) * (11 - i);
rev = 11 - (add % 11);
if (rev == 10 || rev == 11) rev = 0;
if (rev != parseInt(cpf.charAt(10))) return false;

return true; // CPF is valid
}

// Bind the validation to the CPF field
document.addEventListener('DOMContentLoaded', function() {
var cpfField = document.getElementById('cpf'); // Adjust the selector as needed
if (cpfField) {
cpfField.addEventListener('blur', function() {
var isValidCPF = validateCPF(cpfField.value);
if (!isValidCPF) {
alert('CPF INVÁLIDO'); // Provide feedback or handle invalid CPF as needed
// Consider adding more sophisticated feedback mechanisms, such as displaying an error message next to the input field
}
});
}
});
</script>

 I didn’t have too much time to style it and/or display the error message around the field but it should work. 

 

Badge

Hi Hristian, It worked perfectly, I was scratching my head about it... Thank you very much

Reply