Formularz z komunikatami przy polach

Wyjątki i walidacja - JavaScript od podstaw: konsola (HTML/CSS/JS)

Walidacja na stronie po kliknięciu przycisku. Funkcja `validate` zbiera błędy (wszystkie naraz) jako obiekty `{ field, message }`. Przed każdą próbą strona czyści stare komunikaty i ramki, potem przy każdym złym polu wstawia `span` z komunikatem i dodaje polu klasę `invalid`. Gdy błędów nie ma, pokazuje powitanie. Logika walidacji nie wie nic o stronie, a strona nie zna reguł.

<!DOCTYPE html>
<html lang="pl">
<head>
  <meta charset="utf-8">
  <title>Rejestracja</title>
  <style>
    body { font-family: sans-serif; max-width: 34em; }
    label { display: block; margin-top: 0.6em; }
    input, button { font: inherit; padding: 0.2em 0.5em; }
    input.invalid { border: 2px solid #dc2626; }
    .error { color: #dc2626; font-size: 0.9em; margin-left: 0.5em; }
    .ok { color: #15803d; }
  </style>
</head>
<body>
  <h1>Rejestracja</h1>
  <label>Login: <input id="login"></label>
  <label>E-mail: <input id="email"></label>
  <label>Wiek: <input id="age" type="number"></label>
  <p><button id="send">Zarejestruj</button></p>
  <p id="result"></p>
  <script>
    function validate(data) {
      const errors = [];
      if (data.login.trim().length < 3) errors.push({ field: 'login', message: 'co najmniej 3 znaki' });
      if (!data.email.includes('@')) errors.push({ field: 'email', message: 'brak znaku @' });
      const age = Number(data.age);
      if (data.age === '' || !Number.isInteger(age) || age < 13) {
        errors.push({ field: 'age', message: 'wiek: liczba całkowita, co najmniej 13' });
      }
      return errors;
    }

    const fields = ['login', 'email', 'age'];
    document.getElementById('send').addEventListener('click', () => {
      document.querySelectorAll('.error').forEach(span => span.remove());
      const data = {};
      for (const name of fields) {
        const input = document.getElementById(name);
        input.classList.remove('invalid');
        data[name] = input.value;
      }
      const errors = validate(data);
      for (const { field, message } of errors) {
        const input = document.getElementById(field);
        input.classList.add('invalid');
        const span = document.createElement('span');
        span.className = 'error';
        span.textContent = message;
        input.after(span);
      }
      const result = document.getElementById('result');
      result.className = errors.length ? '' : 'ok';
      result.textContent = errors.length ? `Popraw pola: ${errors.length}` : `Witaj, ${data.login}!`;
    });
  </script>
</body>
</html>

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

Wszystkie lekcje kursu JavaScript od podstaw: konsola·Zaloguj się, aby zapisać postęp na koncie.