JAVA FUNCTION SCRIPT CPF VALIDATION

Asked

Viewed 68 times

-2

Hello.

How do I insert the dots and hyphen into the CPF and also restrict the number of digits? Thank you!

function validaCPF(cpf)
  {
    var numeros, digitos, soma, i, resultado, digitos_iguais;
    digitos_iguais = 1;
    if (cpf.length < 11)
          return false;
    for (i = 0; i < cpf.length - 1; i++)
          if (cpf.charAt(i) != cpf.charAt(i + 1))
                {
                digitos_iguais = 0;
                break;
                }
    if (!digitos_iguais)
          {
          numeros = cpf.substring(0,9);
          digitos = cpf.substring(9);
          soma = 0;
          for (i = 10; i > 1; i--)
                soma += numeros.charAt(10 - i) * i;
          resultado = soma % 11 < 2 ? 0 : 11 - soma % 11;
          if (resultado != digitos.charAt(0))
                return false;
          numeros = cpf.substring(0,10);
          soma = 0;
          for (i = 11; i > 1; i--)
                soma += numeros.charAt(11 - i) * i;
          resultado = soma % 11 < 2 ? 0 : 11 - soma % 11;
          if (resultado != digitos.charAt(1))
                return false;
          return true;
          }
    else
        return false;
  }
  • this function only says whether Cpf is valid or not, do you want to make a function that returns the formatted Cpf if it is valid? is this?

  • Mano, next, what you want is called Mascara and not validation Use this plugin https://igorescobar.github.io/jQuery-Mask-Plugin/ $("YOUR identifier"). Mask('999.999.999-99'); success!

  • Okay! Thank you :D

1 answer

0

If you want to format the valid CPF, you can take advantage of this function you created, and simply do something like:

Function to rewrite the value in the desired format:

function format(value, pattern) {
    var i = 0,
        v = value.toString();
    return pattern.replace(/#/g, _ => v[i++]);
}

Function that formats:

function formatCpf(cpf) {
    let cpfValido = validaCPF(cpf)
    if(cpfValido) return format(cpf, '###.###.###-##');
    return cpf;
}
  • Thank you Matheus Ribeiro.

  • Please, if my reply has helped you, mark as the answer

Browser other questions tagged

You are not signed in. Login or sign up in order to post.