Walidacja krok 1: ciąg if-ów

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

Walidacja napisana ręcznie, bez atrybutów HTML. Każde pole ma swoje `if`, komunikaty i czyszczenie błędów są powtórzone, a dodanie reguły oznacza dopisanie kolejnego bloku. Działa, ale rośnie i łatwo coś pominąć (np. wyczyścić stary komunikat).

<!DOCTYPE html>
<html lang="pl">
<head>
  <meta charset="utf-8">
  <title>Walidacja ręczna</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>
    const form = document.getElementById('signup');
    form.addEventListener('submit', e => {
      e.preventDefault();
      let ok = true;
      const login = document.getElementById('login').value.trim();
      document.getElementById('login-error').textContent = '';
      if (login === '') {
        document.getElementById('login-error').textContent = 'Podaj login';
        ok = false;
      } else if (login.length < 3) {
        document.getElementById('login-error').textContent = 'Login: co najmniej 3 znaki';
        ok = false;
      }
      const email = document.getElementById('email').value.trim();
      document.getElementById('email-error').textContent = '';
      if (!email.includes('@')) {
        document.getElementById('email-error').textContent = 'Adres musi mieć @';
        ok = false;
      }
      const age = Number(document.getElementById('age').value);
      document.getElementById('age-error').textContent = '';
      if (!(age >= 10 && age <= 99)) {
        document.getElementById('age-error').textContent = 'Wiek od 10 do 99';
        ok = false;
      }
      document.getElementById('result').textContent = ok ? '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.