🚀 Big News: Socket Acquires Coana to Bring Reachability Analysis to Every Appsec Team.Learn more
Socket
Sign inDemoInstall
Socket

svelte-forms-lib

Package Overview
Dependencies
Maintainers
1
Versions
63
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

svelte-forms-lib

A lightweight library for managing forms in Svelte v3

0.1.11
Source
npm
Version published
Weekly downloads
5.6K
6.21%
Maintainers
1
Weekly downloads
 
Created
Source
Svelte forms lib logo

Svelte forms lib is a lightweight library for managing forms in Svelte, with an Formik like API.

Examples

For examples see the examples folder in or run

npm run examples:start

open up in the browser to see the examples.

Installation

This module is distributed via npm which is bundled with node and should be installed as one of your project's dependencies:

npm install svelte-forms-lib

This package also depends on svelte. Please make sure you have it installed as well.

Usage

<script>
  import createForm from "svelte-forms-lib";

  const { form, handleChange, handleSubmit } = createForm({
    initialValues: {
      name: "",
      email: ""
    },
    onSubmit: values => {
      // make form submission request with `values`
    }
  })
</script>

<form on:submit={handleSubmit}>
  <label for="name">Name</label>
  <input
    type="text"
    name="name"
    bind:value={$form.name}
    on:change={handleChange}
  />

  <label>Email</label>
  <input
    type="email"
    name="email"
    bind:value={$form.email}
    on:change={handleChange}
  />

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

The createForm function requires at minimum a initialValues object which contains the initial state of the form and a submit function which will be called upon submitting the form.

Observables

Because the library is built using the Store API in Svelte, the values exposed by createForm are observables.

// all observables returned by `createForm`
const { form, errors, touched, isValid, isSubmitting, isValidating, state } = createForm({...})

Within the template they can be read using the $ prefix i.e. $form, $errors. For example to access isValid we'll use the $ prefix in the template

<p>This form is {$isValid} </p>

Validation

Using Yup

This library works best with yup for form validation.

<script>
  import createForm from "svelte-forms-lib";
  import yup from "yup";

  const { form, errors, handleChange, handleSubmit } = createForm({
    initialValues: {
      name: "",
      email: ""
    },
    validationSchema: yup.object().shape({
      name: yup.string().required(),
      email: yup.string().email().required()
    }),
    onSubmit: values => {
      // make form submission request with `values`
    }
  })
</script>

<form on:submit={handleSubmit}>
  <label for="name">Name</label>
  <input
    type="text"
    name="name"
    bind:value={$form.name}
    on:change={handleChange}
  />
  {#if $errors.name}
    <em>{$errors.name}</em>
  {/if}

  <label for="email">Email</label>
  <input
    type="email"
    name="email"
    bind:value={$form.email}
    on:change={handleChange}
  />
  {#if $errors.email}
    <em>{$errors.email}</em>
  {/if}

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

Using custom validator

Custom validation is also possible:

<script>
  import createForm from "svelte-forms-lib";
  import yup from "yup";

  const { form, errors, handleChange, handleSubmit } = createForm({
    initialValues: {
      name: "",
      email: ""
    },
    validate: values => {
      let error = {};
      if (values.name === '') {
        error.name = "Name is required"
      }
      if (values.email === '') {
        error.email = "Email is required"
      }
      return error;
    },
    onSubmit: values => {
      // make form submission request with `values`
    }
  })
</script>

<form on:submit={handleSubmit}>
  <label for="name">Name</label>
  <input
    type="text"
    name="name"
    bind:value={$form.name}
    on:change={handleChange}
  />
  {#if $errors.name}
    <em>{$errors.name}</em>
  {/if}

  <label for="email">Email</label>
  <input
    type="email"
    name="email"
    bind:value={$form.email}
    on:change={handleChange}
  />
  {#if $errors.email}
    <em>{$errors.email}</em>
  {/if}

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

Currently custom validation is only run when submitting the form. Field validation will be added in the near future.

Handling form arrays

Svelte forms lib also support form arrays and nested fields. The name attribute in the inputs accept path like strings i.e. users[1].name which allow us to bind to nested properties if the form requires it. See example below. Validation still works as expected.

<script>
  import createForm from "svelte-forms-lib";
  import yup from "yup";

  const { form, errors, state, handleChange, handleSubmit, handleReset } = createForm({
    initialValues: {
      users: [
        {
          name: "",
          email: ""
        }
      ]
    },
    validationSchema: yup.object().shape({
      users: yup.array().of(
        yup.object().shape({
          name: yup.string().required(),
          email: yup
            .string()
            .email()
            .required()
        })
      )
    }),
    onSubmit: ({ values }) => {
      console.log("make form request:", values);
    }
  });

  const add = () => {
    $form.users = $form.users.concat({ name: "", email: "" });
    $errors.users = $errors.users.concat({ name: "", email: "" });
  };

  const remove = i => () => {
    $form.users = $form.users.filter((u, j) => j !== i);
    $errors.users = $errors.users.filter((u, j) => j !== i);
  };
</script>

<form>
  {#each $form.users as user, j}
    <label>name</label>
    <input
      name={`users[${j}].name`}
      on:change={handleChange}
      bind:value={$form.users[j].name} />
    {#if $errors.users[j].name}
      <hint>{$errors.users[j].name}</hint>
    {/if}

    <label>email</label>
    <input
      name={`users[${j}].email`}
      on:change={handleChange}
      bind:value={$form.users[j].email} />
    {#if $errors.users[j].email}
      <hint>{$errors.users[j].email}</hint>
    {/if}

    <button on:click={add}>+</button>
    <button on:click={remove(j)}>-</button>
  {/each}

  <button on:click={handleSubmit}>submit</button>
  <button on:click={handleReset}>reset</button>
</form>

Contributions

Please feel free to submit any issue as means of feedback or create a PR for bug fixes / wanted features.

FAQs

Package last updated on 08 Sep 2019

Did you know?

Socket

Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.

Install

Related posts