Svelte Form Validation

Validation checks that submitted information makes sense before the app uses it. A clear message beside a faulty field saves visitors time and reduces mistakes. Svelte's bindings and reactive logic make the pattern short.

A Basic Validation Pattern

Store field values in variables, store messages in an errors object, and run a validate function on submit. The form proceeds only when the errors object stays empty.

<script>
  let email = "";
  let password = "";
  let errors = {};
  let done = false;

  function validate() {
    const found = {};
    if (!email.includes("@")) found.email = "Enter a valid email address.";
    if (password.length < 8) found.password = "Use at least 8 characters.";
    return found;
  }

  function handleSubmit() {
    errors = validate();
    done = Object.keys(errors).length === 0;
  }
</script>

<form on:submit|preventDefault={handleSubmit} novalidate>
  <label for="email">Email</label>
  <input id="email" bind:value={email} aria-invalid={!!errors.email} />
  {#if errors.email}<p role="alert">{errors.email}</p>{/if}

  <label for="pw">Password</label>
  <input id="pw" type="password" bind:value={password} aria-invalid={!!errors.password} />
  {#if errors.password}<p role="alert">{errors.password}</p>{/if}

  <button>Create Account</button>
</form>
{#if done}<p>All fields look good.</p>{/if}

The novalidate attribute turns off the browser's default bubbles, so your own messages take over.

Validation Flow Diagram

Visitor presses Create Account
          |
          v
   handleSubmit() runs
          |
          v
   validate() checks each field
          |
     +----+-----------------+
     |                      |
Errors found           No errors
     |                      |
Show messages          Send data onward
beside fields

Live Validation With Reactive Statements

A reactive declaration can check fields while the visitor types. Show messages only after the visitor leaves a field, so the form does not scold anyone who has barely started.

<script>
  let username = "";
  let touched = false;

  $: usernameError =
    username.length < 3 ? "Username needs 3 or more characters." : "";
</script>

<input bind:value={username} on:blur={() => (touched = true)} />
{#if touched && usernameError}
  <p role="alert">{usernameError}</p>
{/if}

Disabling The Submit Button

A derived flag can keep the button disabled until every rule passes. Pair the flag with visible messages, since a silent disabled button leaves visitors guessing.

$: isValid = email.includes("@") && password.length >= 8;

<button disabled={!isValid}>Create Account</button>

Accessible Error Messages

  • Connect each label to its input with matching for and id values
  • Set aria-invalid on fields that fail
  • Use role alert so screen readers announce new messages
  • Write messages that explain the fix, not only the problem

Always Validate On The Server

Browser checks guide honest visitors. They cannot stop someone who bypasses the page and sends data directly. The server must repeat every important check before it saves anything.

A Layman Analogy

Think of an airport check-in desk. The agent checks the passport, the ticket, and the baggage weight before the traveler walks to the gate. Each failed check comes with a clear instruction, such as moving one item to a carry-on bag. The server acts as the security gate at the end, where officers verify everything again.

Common Mistakes To Avoid

  • Showing errors on empty fields before the visitor types anything
  • Writing vague messages such as Invalid input
  • Trusting browser validation without a server check
  • Clearing the form after an error, which forces visitors to retype everything

Key Points

  • An errors object keeps messages organized by field
  • The touched flag delays messages until visitors finish a field
  • Accessible markup helps every visitor understand problems
  • Server-side validation remains mandatory