Skip to content

wetix/svelte-reactive-form

Repository files navigation

Svelte Reactive Form

A better version of form validation for Svelte.

Svelte v3 npm Build Status download Bundle Size LICENCE

NPM Stat

Installation and Usage

npm install svelte-reactive-form

or

yarn add svelte-reactive-form

Features

  • Simple
  • No extra dependency
  • TypeScript as first class citizen
  • Custom validation
  • Reactive
  • Flexible & Configurable

How to use

https://svelte.dev/repl/2afb74650f36429fa15871b6998d60c9?version=3.31.0

<script lang="ts">
  import { useForm, Field, defineRule } from "svelte-reactive-form";
  import { required, minLength } from "@svelte-reactive-form/rules";

  // define the global validation rules
  defineRule("required", required);
  defineRule("minLength", minLength);
  defineRule("numeric", (val: any) => {
    return /[0-9]+/.test(val) || "invalid numeric format";
  });

  // initialize the form instance
  const form$ = useForm<{ name: string; pin: string; description: string }>();
  const { field, register, setValue, control, onSubmit } = form$;

  // you can register your field manually
  register("pin", {
    defaultValue: "",
    rules: ["required", "minLength:4", "numeric"]
  });

  const submitCallback = onSubmit((data, e) => {
    console.log("Data =>", data);
    console.log("Event =>", e);
  }, (err, e) => {
    console.log("Error =>", err);
    console.log("Event =>", e);
  });
</script>

<form on:submit={submitCallback}>
  <Field {control} name="name" rules="required" let:errors let:onChange>
    <Component {onChange} />
    {#each errors as item}
        <div>{item}</div>
    {/each}
  </Field>
  <!-- manually handle set value -->
  <input type="text" on:input={(e) => setValue("pin", e.target.value)} />
  <!-- register field using svelte actions -->
  <input name="description" type="text" use:field={{ rules: ["required"] }}>
  <button disabled={!$form$.valid}>
    {#if $form$.submitting}Submit{:else}Submiting...{/if}
  </button>
</form>

API

Check out the API documentation.

For advanced usage, you may refer to Advanced API.

Sponsors

WeTix

License

svelve-reactive-form is 100% free and open-source, under the MIT license.

Big Thanks To

Thanks to these awesome companies for their support of Open Source developers ❤

GitHub NPM

Inspired by react-hook-form.