script.js 5.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156
  1. const validarCpf = (cpf) => {
  2. if (cpf.length != 11) return false;
  3. else {
  4. var numeros = cpf.substring(0, 9)
  5. var digitos = cpf.substring(9)
  6. var soma = 0;
  7. for (var i = 10; i > 1; i--) {
  8. soma += numeros.charAt(10 - i) * i;
  9. }
  10. var resultado = (soma % 11) < 2 ? 0 : 11 - (soma % 11);
  11. if (resultado != digitos.charAt(0)) {
  12. return false;
  13. }
  14. var soma = 0;
  15. numeros = cpf.substring(0, 10);
  16. for (var k = 11; k > 1; k--) {
  17. soma += numeros.charAt(11 - k) * k;
  18. }
  19. resultado = soma % 11 < 2 ? 0 : 11 - (soma % 11);
  20. if (resultado != digitos.charAt(1)) {
  21. return false;
  22. } else return true;
  23. }
  24. }
  25. function validacao() {
  26. var cpf = document.getElementById("cpf").value.replace(/[^a-z0-9 ]/g, "")
  27. var validInputs = document.querySelectorAll(".required")
  28. var resultadoValidacao = validarCpf(cpf)
  29. for (i = 0; i < validInputs.length; i++) {
  30. if (validInputs[i].value === undefined || validInputs[i].value === "") validInputs[i].style["border"] = "1px solid red"
  31. }
  32. for (i = 0; i < validInputs.length; i++) {
  33. if (validInputs[i].value === undefined || validInputs[i].value === "") {
  34. resultadoValidacao = false;
  35. break
  36. } else {
  37. resultadoValidacao = true
  38. validInputs[1].style["border"] = "none"
  39. validInputs[i].style["border"] = "none"
  40. document.querySelector("span").style["display"] = "none"
  41. }
  42. }
  43. if (resultadoValidacao && validarCpf(cpf)) {
  44. window.alert("Parabens!! voce foi cadastrado com sucesso");
  45. return true
  46. } else if (!validarCpf(cpf)) {
  47. window.alert("Opss! Aconteceu um erro no seu cadastro, verifique se voce preencheu todos espacos necessarios")
  48. validInputs[1].style["border"] = "1px solid red"
  49. document.querySelector("span").style["display"] = "inline"
  50. return false
  51. }
  52. else {
  53. window.alert("Opss! Aconteceu um erro no seu cadastro, verifique se voce preencheu todos espacos necessarios")
  54. return false
  55. }
  56. }
  57. function limpa_formulário_cep() {
  58. //Limpa valores do formulário de cep.
  59. document.getElementById('endereco').value = ("");
  60. document.getElementById('bairro').value = ("");
  61. document.getElementById('cidade').value = ("");
  62. document.getElementById('estado').value = ("");
  63. }
  64. function meu_callback(conteudo) {
  65. if (!("erro" in conteudo)) {
  66. //Atualiza os campos com os valores.
  67. document.getElementById('endereco').value = (conteudo.logradouro);
  68. document.getElementById('bairro').value = (conteudo.bairro);
  69. document.getElementById('cidade').value = (conteudo.localidade);
  70. document.getElementById('estado').value = (conteudo.uf);
  71. }
  72. else {
  73. //CEP não Encontrado.
  74. limpa_formulário_cep();
  75. alert("CEP não encontrado.");
  76. }
  77. }
  78. function pesquisacep(valor) {
  79. //Nova variável "cep" somente com dígitos.
  80. var cep = valor.replace(/\D/g, '');
  81. //Verifica se campo cep possui valor informado.
  82. if (cep != "") {
  83. //Expressão regular para validar o CEP.
  84. var validacep = /^[0-9]{8}$/;
  85. //Valida o formato do CEP.
  86. if (validacep.test(cep)) {
  87. //Cria um elemento javascript.
  88. var script = document.createElement('script');
  89. //Sincroniza com o callback.
  90. script.src = 'https://viacep.com.br/ws/' + cep + '/json/?callback=meu_callback';
  91. //Insere script no documento e carrega o conteúdo.
  92. document.body.appendChild(script);
  93. } //end if.
  94. else {
  95. //cep é inválido.
  96. limpa_formulário_cep();
  97. alert("Formato de CEP inválido.");
  98. }
  99. } //end if.
  100. else {
  101. //cep sem valor, limpa formulário.
  102. limpa_formulário_cep();
  103. }
  104. };
  105. document.addEventListener('DOMContentLoaded', () => {
  106. for (const el of document.querySelectorAll("[placeholder][data-slots]")) {
  107. const pattern = el.getAttribute("placeholder"),
  108. slots = new Set(el.dataset.slots || "_"),
  109. prev = (j => Array.from(pattern, (c,i) => slots.has(c)? j=i+1: j))(0),
  110. first = [...pattern].findIndex(c => slots.has(c)),
  111. accept = new RegExp(el.dataset.accept || "\\d", "g"),
  112. clean = input => {
  113. input = input.match(accept) || [];
  114. return Array.from(pattern, c =>
  115. input[0] === c || slots.has(c) ? input.shift() || c : c
  116. );
  117. },
  118. format = () => {
  119. const [i, j] = [el.selectionStart, el.selectionEnd].map(i => {
  120. i = clean(el.value.slice(0, i)).findIndex(c => slots.has(c));
  121. return i<0? prev[prev.length-1]: back? prev[i-1] || first: i;
  122. });
  123. el.value = clean(el.value).join``;
  124. el.setSelectionRange(i, j);
  125. back = false;
  126. };
  127. let back = false;
  128. el.addEventListener("keydown", (e) => back = e.key === "Backspace");
  129. el.addEventListener("input", format);
  130. el.addEventListener("focus", format);
  131. el.addEventListener("blur", () => el.value === pattern && (el.value=""));
  132. }
  133. });