Validate CPF with JavaScript Regular Expression

4

Well, I'm trying to validate CPF with regular expressions only. I have already been able to validate the format ... 000.000.000-10

^([0-9]){3}\.([0-9]){3}\.([0-9]){3}-([0-9]){2}$

Now, is there a way to validate if the CPF is valid in relation to the verification digits?

If possible, how?

Thankful ...

    
asked by anonymous 16.04.2016 / 07:00

1 answer

8

There is no way to validate CPF with regex because it has an account involved, it is not just validating the mask.

Use this function or whatever you find, but regex you will not be able to.

function validarCPF(inputCPF){
    var soma = 0;
    var resto;
    var inputCPF = document.getElementById('cpf').value;

    if(inputCPF == '00000000000') return false;
    for(i=1; i<=9; i++) soma = soma + parseInt(inputCPF.substring(i-1, i)) * (11 - i);
    resto = (soma * 10) % 11;

    if((resto == 10) || (resto == 11)) resto = 0;
    if(resto != parseInt(inputCPF.substring(9, 10))) return false;

    soma = 0;
    for(i = 1; i <= 10; i++) soma = soma + parseInt(inputCPF.substring(i-1, i))*(12-i);
    resto = (soma * 10) % 11;

    if((resto == 10) || (resto == 11)) resto = 0;
    if(resto != parseInt(inputCPF.substring(10, 11))) return false;
    return true;
}
    
16.04.2016 / 07:09