checkValidity i obiekt validity

Walidacja formularzy: HTML i JavaScript - JavaScript na stronach WWW (HTML/CSS/JS)

Atrybut `novalidate` wyłącza dymki przeglądarki, ale reguły z atrybutów nadal działają: `pole.checkValidity()` mówi, czy pole jest poprawne, a obiekt `pole.validity` mówi DLACZEGO nie jest (`valueMissing`, `tooShort`, `typeMismatch`, `rangeUnderflow`, `rangeOverflow`...). Skrypt zamienia te flagi na własne komunikaty obok pól. Reguły zostają w HTML, a wygląd błędów należy do strony.

<!DOCTYPE html>
<html lang="pl">
<head>
  <meta charset="utf-8">
  <title>validity</title>
  <style>
    body { font-family: sans-serif; max-width: 36em; line-height: 1.4; }
    input, select, button, textarea { font: inherit; padding: 0.2em 0.4em; }
    table { border-collapse: collapse; }
    th, td { border: 1px solid #94a3b8; padding: 0.2em 0.6em; }

    input:invalid { border-color: #dc2626; }
    .error { color: #dc2626; font-size: 0.9em; }
    input.error { border: 2px solid #dc2626; color: inherit; }
  </style>
</head>
<body>
  <form id="signup" novalidate>
    <p><label>Login: <input id="login" required minlength="3" maxlength="12"></label> <span class="error" id="login-error"></span></p>
    <p><label>E-mail: <input id="email" type="email" required></label> <span class="error" id="email-error"></span></p>
    <p><label>Wiek: <input id="age" type="number" required min="10" max="99"></label> <span class="error" id="age-error"></span></p>
    <button>Załóż konto</button>
  </form>
  <p id="result"></p>
  <script>
    function messageFor(input) {
      const v = input.validity;
      if (v.valueMissing) return 'To pole jest wymagane';
      if (v.tooShort) return `Co najmniej ${input.minLength} znaki`;
      if (v.typeMismatch) return 'To nie wygląda na adres e-mail';
      if (v.rangeUnderflow) return `Najmniej ${input.min}`;
      if (v.rangeOverflow) return `Najwięcej ${input.max}`;
      return '';
    }

    const form = document.getElementById('signup');
    form.addEventListener('submit', e => {
      e.preventDefault();
      for (const input of form.querySelectorAll('input')) {
        document.getElementById(input.id + '-error').textContent = messageFor(input);
      }
      document.getElementById('result').textContent = form.checkValidity()
        ? 'Konto założone'
        : 'Popraw zaznaczone pola';
    });
  </script>
</body>
</html>

Ładowanie interaktywnego edytora... Jeśli się nie pojawi, włącz JavaScript.

Wszystkie lekcje kursu JavaScript na stronach WWW·Zaloguj się, aby zapisać postęp na koncie.