Written by: Geoffrey Callaghan

Handling Forms in Svelte

Handling Forms In Svelte

Handling forms in Svelte is straightforward and can be done efficiently with its reactivity and built-in form handling capabilities. Here’s a guide to creating and managing forms in Svelte, including validation and form submission.

1. Basic Form Handling

Creating a basic form in Svelte involves using standard HTML form elements and binding them to Svelte variables using the bind directive.

Example

<script>
  let name = '';
  let email = '';

  function handleSubmit() {
    console.log('Name:', name);
    console.log('Email:', email);
  }
</script>

<form on:submit|preventDefault={handleSubmit}>
  <label for="name">Name:</label>
  <input id="name" type="text" bind:value={name} />

  <label for="email">Email:</label>
  <input id="email" type="email" bind:value={email} />

  <button type="submit">Submit</button>
</form>

2. Validation

Svelte doesn’t have built-in validation utilities like some frameworks, but you can easily implement validation logic within your component.

Example with Basic Validation

<script>
  let name = '';
  let email = '';
  let errors = { name: '', email: '' };

  function handleSubmit() {
    errors = { name: '', email: '' };

    if (!name) {
      errors.name = 'Name is required';
    }

    const emailPattern = /^[^@\s]+@[^@\s]+\.[^@\s]+$/;
    if (!email || !emailPattern.test(email)) {
      errors.email = 'Invalid email address';
    }

    if (!errors.name && !errors.email) {
      console.log('Form Submitted:', { name, email });
    }
  }
</script>

<form on:submit|preventDefault={handleSubmit}>
  <label for="name">Name:</label>
  <input id="name" type="text" bind:value={name} />
  {#if errors.name}
    <span class="error">{errors.name}</span>
  {/if}

  <label for="email">Email:</label>
  <input id="email" type="email" bind:value={email} />
  {#if errors.email}
    <span class="error">{errors.email}</span>
  {/if}

  <button type="submit">Submit</button>
</form>

<style>
  .error {
    color: red;
    font-size: 0.8em;
  }
</style>

3. Resetting the Form

To reset form fields, you can simply reassign the bound variables to their initial values.

Example with Form Reset

<script>
  let name = '';
  let email = '';

  function handleSubmit() {
    console.log('Name:', name);
    console.log('Email:', email);
    resetForm();
  }

  function resetForm() {
    name = '';
    email = '';
  }
</script>

<form on:submit|preventDefault={handleSubmit}>
  <label for="name">Name:</label>
  <input id="name" type="text" bind:value={name} />

  <label for="email">Email:</label>
  <input id="email" type="email" bind:value={email} />

  <button type="submit">Submit</button>
  <button type="button" on:click={resetForm}>Reset</button>
</form>

4. Advanced Validation with Svelte Form Libraries

For more advanced form handling and validation, you can use third-party libraries like svelte-forms-lib or felte.

Example with svelte-forms-lib

  1. Install the library:
npm install svelte-forms-lib
  1. Usage:
<script>
  import { useForm } from 'svelte-forms-lib';
  
  const { form, errors, handleSubmit, handleReset, register } = useForm({
    initialValues: {
      name: '',
      email: '',
    },
    validate: values => {
      const errors = {};
      if (!values.name) {
        errors.name = 'Name is required';
      }
      if (!values.email) {
        errors.email = 'Email is required';
      } else if (!/^[^@\s]+@[^@\s]+\.[^@\s]+$/.test(values.email)) {
        errors.email = 'Invalid email address';
      }
      return errors;
    },
    onSubmit: values => {
      console.log('Form Submitted:', values);
    },
  });
</script>

<form on:submit|preventDefault={handleSubmit}>
  <label for="name">Name:</label>
  <input id="name" type="text" {...register('name')} />
  {#if errors.name}
    <span class="error">{errors.name}</span>
  {/if}

  <label for="email">Email:</label>
  <input id="email" type="email" {...register('email')} />
  {#if errors.email}
    <span class="error">{errors.email}</span>
  {/if}

  <button type="submit">Submit</button>
  <button type="button" on:click={handleReset}>Reset</button>
</form>

<style>
  .error {
    color: red;
    font-size: 0.8em;
  }
</style>

Conclusion

Handling forms in Svelte is intuitive and flexible. You can start with basic form handling using built-in Svelte features and scale up to more advanced use cases with libraries like svelte-forms-lib for comprehensive form management and validation. This approach ensures your forms are both user-friendly and maintainable.