Advertisement
Mary_Pieroszkiewicz

Walidacja formularza JS

May 21st, 2020
1,177
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. const toggleErrorField = function(field, show) {
  2.   const errorText = field.nextElementSibling;
  3.   if (errorText !== null) {
  4.     if (errorText.classList.contains('form-error-text')) {
  5.       errorText.style.display = ? 'block' : 'none';
  6.       errorText.setAttribute('aria-hidden', show);
  7.     }
  8.   }
  9. };
  10.  
  11. const markFieldAsError = function(field, show) {
  12.   if (show) {
  13.     field.classList.add("field-error");
  14.   } else {
  15.     field.classList.remove("field-error");
  16.     toggleErrorField(field, false);
  17.   }
  18. };
  19.  
  20. const form = document.querySelector('#contactForm');
  21. const inputName = form.querySelector('input[name=name]');
  22. const inputSurname = form.querySelector('input[name=surname]');
  23. const inputEmail = form.querySelector('input[name=email]');
  24. const formMessage = form.querySelector('input[name=message]');
  25.  
  26. form.setAttribute('novalidate', true);
  27.  
  28. const inputs = [inputName, inputSurname, inputEmail];
  29. for (const el of inputs) {
  30.   el.addEventListener("input", e => markFieldAsError(e.target, !e.target.checkValidity()));
  31. }
  32.  
  33. form.addEventListener("submit", e => {
  34.   e.preventDefault();
  35.  
  36.   let formErrors = false;
  37.  
  38.   //2 etap - sprawdzamy poszczególne pola gdy ktoś chce wysłać formularz
  39.   for (const el of inputs) {
  40.     markFieldAsError(el, false);
  41.     toggleErrorField(el, false);
  42.  
  43.     if (!el.checkValidity()) {
  44.       markFieldAsError(el, true);
  45.       toggleErrorField(el, true);
  46.       formErrors = true;
  47.     }
  48.   }
  49.  
  50.   if (!formErrors) {
  51.     const submit = form.querySelector("[type=submit]");
  52.     submit.disabled = true;
  53.     submit.classList.add("element-is-busy");
  54.  
  55.     const formData = new FormData();
  56.     for (const el of inputs) {
  57.       formData.append(el.name, el.value)
  58.     }
  59.  
  60.     const url = form.getAttribute("action");
  61.     const method = form.getAttribute("method");
  62.  
  63.     fetch(url, {
  64.       method: method.toUpperCase(),
  65.       body: formData
  66.     })
  67.         .then(res => res.json())
  68.         .then(res => {
  69.           if (res.errors) {
  70.             const selectors = res.errors.map(el => `[name="${el}"]`);
  71.             const fieldsWithErrors = form.querySelectorAll(selectors.join(","));
  72.             for (const el of fieldsWithErrors) {
  73.               markFieldAsError(el, true);
  74.               toggleErrorField(el, true);
  75.             }
  76.           } else {
  77.             if (res.status === "ok") {
  78.               const div = document.createElement("div");
  79.               div.classList.add("form-send-success");
  80.               div.innerText = "Wysłanie wiadomości się nie powiodło";
  81.  
  82.               form.parentElement.insertBefore(div, form);
  83.               div.innerHTML = `
  84.                         <strong>Wiadomość została wysłana</strong>
  85.                         <span>Dziękujemy za kontakt. Postaramy się odpowiedzieć jak najszybciej</span>
  86.                     `;
  87.               form.remove();
  88.             }
  89.             if (res.status === "error") {
  90.               //jeżeli istnieje komunikat o błędzie wysyłki
  91.               //np. generowany przy poprzednim wysyłaniu formularza
  92.               //usuwamy go, by nie duplikować tych komunikatów
  93.               const statusError = document.querySelector(".send-error");
  94.               if (statusError) {
  95.                 statusError.remove();
  96.               }
  97.  
  98.               const div = document.createElement("div");
  99.               div.classList.add("send-error");
  100.               div.innerText = "Wysłanie wiadomości się nie powiodło";
  101.               submit.parentElement.appendChild(div);
  102.             }
  103.           }
  104.         }).finally(() => {
  105.       submit.disabled = false;
  106.       submit.classList.remove("element-is-busy");
  107.     });
  108.   }
  109. });
  110.  
  111. document.querySelector("#loadingTest").addEventListener("click", function() {
  112.   this.classList.add("element-is-busy");
  113.   this.disabled = true;
  114. });
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement