A better version of form validation for Svelte.
npm install svelte-reactive-form
or
yarn add svelte-reactive-form
- Simple
- No extra dependency
- TypeScript as first class citizen
- Custom validation
- Reactive
- Flexible & Configurable
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>
Check out the API documentation.
For advanced usage, you may refer to Advanced API.
svelve-reactive-form is 100% free and open-source, under the MIT license.
Thanks to these awesome companies for their support of Open Source developers ❤
Inspired by react-hook-form.