Skip to content

Instantly share code, notes, and snippets.

@nagawaka
Last active July 10, 2019 21:39
Show Gist options
  • Save nagawaka/86736811928eec814166a2098761e4c6 to your computer and use it in GitHub Desktop.
Save nagawaka/86736811928eec814166a2098761e4c6 to your computer and use it in GitHub Desktop.
Few code snippets (JS)

Processing map

const normalize = (value, start1, stop1, start2, stop2, stopAtStop2) => {
  const retVal = (start2 + (stop2 - start2) * ((value - start1) / (stop1 - start1)))
  return (stopAtStop2 ? (retVal < stop2 ? stop2 : retVal) : retVal);
}

CPF Validation

const cpfValidation = (cpf = '') => {
  cpf = cpf.replace(/[^\d]+/g, '');
  if (cpf == '') return false;
  // Elimina CPFs invalidos conhecidos
  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;
  // Valida 1º digito
  let add = 0;
  for (let 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;
  // Valida 2º digito
  add = 0;
  for (let i = 0; i < 10; i++)
    add += parseInt(cpf.charAt(i)) * (11 - i);
  let rev = 11 - (add % 11);
  if (rev == 10 || rev == 11)
    rev = 0;
  if (rev != parseInt(cpf.charAt(10)))
    return false;
  return true;
}

CNPJ Validation

const validationCNPJ = (c) => {
  var b = [6,5,4,3,2,9,8,7,6,5,4,3,2];

  if((c = c.replace(/[^\d]/g,"")).length != 14)
      return false;

  if(/0{14}/.test(c))
      return false;

  for (var i = 0, n = 0; i < 12; n += c[i] * b[++i]);
  if(c[12] != (((n %= 11) < 2) ? 0 : 11 - n))
      return false;

  for (var i = 0, n = 0; i <= 12; n += c[i] * b[i++]);
  if(c[13] != (((n %= 11) < 2) ? 0 : 11 - n))
      return false;

  return true;
}

Email validation

const emailValidation = mail => {
  const ret = mail && !/^[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,}$/i.test(mail.trim())
    ? false
    : true;
  return ret;
};

export default emailValidation;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment