Unlock the Power of Forms in Svelte

Tracking User Input with Svelte

Forms are an essential part of web development, and Svelte is no exception. To create robust and user-friendly forms, you need to track user input, validate data, and handle form submissions.

Svelte provides two directives to track user input: on:input and bind:value. While on:input requires a handleInput event, bind:value offers a cleaner way to work with form values. We’ll use bind:value to simplify our form development process.

<input bind:value={name} />

Validating Forms with Yup

Yup is a popular JavaScript object schema validator that ensures data conforms to a specific structure. By defining a schema, you can validate objects and guarantee that the data sent to the server is valid.

const schema = yup.object().shape({
  name: yup.string().required(),
  email: yup.string().email().required(),
});

We’ll create a profile form and validate it using Yup’s validate method.

schema.validate(values, { abortEarly: false })
 .then(() => {
    // Form is valid
  })
 .catch((err) => {
    // Form is invalid
  });

Creating a Profile Form with Svelte

Let’s set up a simple profile form to capture user data. We’ll bind the form fields to a values object and create an errors object to store validation errors. Our handleSubmit function will handle form validation and submission.

<form on:submit={handleSubmit}>
  <label>Name:</label>
  <input bind:value={values.name} />
  <br>
  <label>Email:</label>
  <input bind:value={values.email} />
  <br>
  <button type="submit">Submit</button>
</form>

Displaying Validation Errors

To display errors, we’ll loop over Yup’s validation error.inner array and create a new object with fields and error messages. We’ll then update the errors object with the corresponding input field errors.

const errors = {};
err.inner.forEach((error) => {
  errors[error.path] = error.message;
});

Simplifying Form Development with svelte-forms-lib

svelte-forms-lib is a Formik-inspired library that makes building forms in Svelte easier. We’ll explore how to integrate svelte-forms-lib into our form, using its createForm function, observables, and helper functions like handleChange and handleSubmit.

import { createForm } from 'velte-forms-lib';

const form = createForm({
  values: {
    name: '',
    email: '',
  },
  validationSchema: schema,
});

Custom Validation with svelte-forms-lib

We’ll learn how to add a custom validation callback to createForm, checking the state of each input field and updating the errors object accordingly.

const form = createForm({
  values: {
    name: '',
    email: '',
  },
  validate: (values) => {
    const errors = {};
    // Custom validation logic
    return errors;
  },
});

Yup Validation in svelte-forms-lib

svelte-forms-lib also supports Yup validation through the validationSchema prop. We’ll pass in our schema object and let svelte-forms-lib handle the validation.

const form = createForm({
  values: {
    name: '',
    email: '',
  },
  validationSchema: schema,
});

Custom Form Components in svelte-forms-lib

To reduce boilerplate code, svelte-forms-lib provides custom components like <Form/>, <Field/>, <Select/>, and <ErrorMessage/>. We’ll use these components to create a concise and efficient form.

<Form>
  <Field name="name">
    <input />
    <ErrorMessage>{errors.name}</ErrorMessage>
  </Field>
  <Field name="email">
    <input />
    <ErrorMessage>{errors.email}</ErrorMessage>
  </Field>
  <button type="submit">Submit</button>
</Form>

Leave a Reply