Validar CPF com JavaScript

65d atrás

0 0

A função #JavaScript abaixo valida CPFs, retornando true se for válido ou false se inválido.

function isValidCpf(cpf) {
  cpf = cpf.replace(/\D/g, '');

  if (cpf.toString().length != 11 || /^(\d)\1{10}$/.test(cpf)) return false;

  let result = true;
  
  [9, 10].forEach(function(j) {
    let 
      soma = 0,
      r = null;

    cpf.split(/(?=)/).splice(0, j).forEach(function(e, i) {
      soma += parseInt(e) * ((j + 2) - (i + 1));
    });

    r = soma % 11;

    r = (r < 2) ? 0 : 11 - r;

    if (r.toString() != cpf.substring(j, j + 1)) result = false;
  });

  return result;
}

Alguns exemplos de uso da função:

isValidCpf('111.111.111-11'); // false
isValidCpf('22222222222'); // false
isValidCpf('490.759.660-08'); // true
isValidCpf('20967215048'); // true


Comentários (0)

0/512
Link