This page introduces the basic concepts and terminology used in the @tanstack/svelte-form library. Familiarizing yourself with these concepts will help you better understand and work with the library.
You can create options for your form so that it can be shared between multiple forms by using the formOptions function.
Example:
const formOpts = formOptions({
defaultValues: {
firstName: '',
lastName: '',
hobbies: [],
} as Person,
})
const formOpts = formOptions({
defaultValues: {
firstName: '',
lastName: '',
hobbies: [],
} as Person,
})
A Form Instance is an object that represents an individual form and provides methods and properties for working with the form. You create a form instance using the createForm function. The function accepts an object with an onSubmit function, which is called when the form is submitted.
const form = createForm(() => ({
...formOpts,
onSubmit: async ({ value }) => {
// Do something with form data
console.log(value)
},
}))
const form = createForm(() => ({
...formOpts,
onSubmit: async ({ value }) => {
// Do something with form data
console.log(value)
},
}))
You may also create a form instance without using formOptions:
const form = createForm<Person>(() => ({
onSubmit: async ({ value }) => {
// Do something with form data
console.log(value)
},
defaultValues: {
firstName: '',
lastName: '',
hobbies: [],
},
}))
const form = createForm<Person>(() => ({
onSubmit: async ({ value }) => {
// Do something with form data
console.log(value)
},
defaultValues: {
firstName: '',
lastName: '',
hobbies: [],
},
}))
A Field represents a single form input element, such as a text input or a checkbox. Fields are created using the form.Field component provided by the form instance. The component accepts a name prop, which should match a key in the form's default values. It also accepts a children prop, which is a render prop function that takes a field object as its argument.
Example:
<form.Field name="firstName">
{#snippet children(field)}
<input
name={field.name}
value={field.state.value}
onblur={field.handleBlur}
oninput={(e) => field.handleChange(e.target.value)}
/>
{/snippet}
</form.Field>
<form.Field name="firstName">
{#snippet children(field)}
<input
name={field.name}
value={field.state.value}
onblur={field.handleBlur}
oninput={(e) => field.handleChange(e.target.value)}
/>
{/snippet}
</form.Field>
Each field has its own state, which includes its current value, validation status, error messages, and other metadata. You can access a field's state using the field.state property.
Example:
const {
value,
meta: { errors, isValidating },
} = field.state
const {
value,
meta: { errors, isValidating },
} = field.state
There are three field states can be very useful to see how the user interacts with a field. A field is "touched" when the user clicks/tabs into it, "pristine" until the user changes value in it, and "dirty" after the value has been changed. You can check these states via the isTouched, isPristine and isDirty flags, as seen below.
const { isTouched, isPristine, isDirty } = field.state.meta
const { isTouched, isPristine, isDirty } = field.state.meta
The Field API is an object passed to the render prop function when creating a field. It provides methods for working with the field's state.
Example:
<input
name={field.name}
value={field.state.value}
onblur={field.handleBlur}
oninput={(e) => field.handleChange(e.target.value)}
/>
<input
name={field.name}
value={field.state.value}
onblur={field.handleBlur}
oninput={(e) => field.handleChange(e.target.value)}
/>
@tanstack/svelte-form provides both synchronous and asynchronous validation out of the box. Validation functions can be passed to the form.Field component using the validators prop.
Example:
<form.Field
name="firstName"
validators={{
onChange: ({ value }) =>
!value
? 'A first name is required'
: value.length < 3
? 'First name must be at least 3 characters'
: undefined,
onChangeAsync: async ({ value }) => {
await new Promise((resolve) => setTimeout(resolve, 1000))
return value.includes('error') && 'No "error" allowed in first name'
},
}}
>
{#snippet children(field)}
<input
name={field.name}
value={field.state.value}
onBlur={field.handleBlur}
onInput={(e) => field.handleChange(e.target.value)}
/>
<p>{field.state.meta.errors[0]}</p>
{/snippet}
</form.Field>
<form.Field
name="firstName"
validators={{
onChange: ({ value }) =>
!value
? 'A first name is required'
: value.length < 3
? 'First name must be at least 3 characters'
: undefined,
onChangeAsync: async ({ value }) => {
await new Promise((resolve) => setTimeout(resolve, 1000))
return value.includes('error') && 'No "error" allowed in first name'
},
}}
>
{#snippet children(field)}
<input
name={field.name}
value={field.state.value}
onBlur={field.handleBlur}
onInput={(e) => field.handleChange(e.target.value)}
/>
<p>{field.state.meta.errors[0]}</p>
{/snippet}
</form.Field>
In addition to hand-rolled validation options, we also support the Standard Schema specification.
You can define a schema using any of the libraries implementing the specification and pass it to a form or field validator.
Supported libraries include:
<script>
import { z } from 'zod'
// ...
</script>
<form.Field
name="firstName"
validators={{
onChange: z.string().min(3, 'First name must be at least 3 characters'),
onChangeAsyncDebounceMs: 500,
onChangeAsync: z.string().refine(
async (value) => {
await new Promise((resolve) => setTimeout(resolve, 1000))
return !value.includes('error')
},
{
message: 'No "error" allowed in first name',
},
),
}}
>
{#snippet children(field)}
<input
name={field.name}
value={field.state.value}
onBlur={field.handleBlur}
onInput={(e) => field.handleChange(e.target.value)}
/>
<p>{field.state.meta.errors[0]}</p>
{/snippet}
</form.Field>
<script>
import { z } from 'zod'
// ...
</script>
<form.Field
name="firstName"
validators={{
onChange: z.string().min(3, 'First name must be at least 3 characters'),
onChangeAsyncDebounceMs: 500,
onChangeAsync: z.string().refine(
async (value) => {
await new Promise((resolve) => setTimeout(resolve, 1000))
return !value.includes('error')
},
{
message: 'No "error" allowed in first name',
},
),
}}
>
{#snippet children(field)}
<input
name={field.name}
value={field.state.value}
onBlur={field.handleBlur}
onInput={(e) => field.handleChange(e.target.value)}
/>
<p>{field.state.meta.errors[0]}</p>
{/snippet}
</form.Field>
@tanstack/svelte-form offers various ways to subscribe to form and field state changes, most notably the form.useStore hook and the form.Subscribe component. These methods allow you to optimize your form's rendering performance by only updating components when necessary.
Example:
<script>
//...
const firstName = form.useStore((state) => state.values.firstName)
</script>
<form.Subscribe
selector={(state) => ({
canSubmit: state.canSubmit,
isSubmitting: state.isSubmitting,
})}
>
{#snippet children(state)}
<button type="submit" disabled={!state.canSubmit}>
{state.isSubmitting ? '...' : 'Submit'}
</button>
{/snippet}
</form.Subscribe>
<script>
//...
const firstName = form.useStore((state) => state.values.firstName)
</script>
<form.Subscribe
selector={(state) => ({
canSubmit: state.canSubmit,
isSubmitting: state.isSubmitting,
})}
>
{#snippet children(state)}
<button type="submit" disabled={!state.canSubmit}>
{state.isSubmitting ? '...' : 'Submit'}
</button>
{/snippet}
</form.Subscribe>
Array fields allow you to manage a list of values within a form, such as a list of hobbies. You can create an array field using the form.Field component with the mode="array" prop.
When working with array fields, you can use the fields pushValue, removeValue, swapValues and moveValue methods to add, remove, and swap values in the array.
Example:
<form.Field name="hobbies" mode="array">
{#snippet children(hobbiesField)}
<div>
Hobbies
<div>
{#each hobbiesField.state.value as _, i}
<div>
<form.Field name={`hobbies[${i}].name`}>
{#snippet children(field)}
<div>
<label for={field.name}>Name:</label>
<input
id={field.name}
name={field.name}
value={field.state.value}
onblur={field.handleBlur}
onchange={(e) => field.handleChange(e.target.value)}
/>
<button
type="button"
onclick={() => hobbiesField.removeValue(i)}
>
X
</button>
</div>
{/snippet}
</form.Field>
<form.Field name={`hobbies[${i}].description`}>
{#snippet children(field)}
<div>
<label for={field.name}>Description:</label>
<input
id={field.name}
name={field.name}
value={field.state.value}
onblur={field.handleBlur}
onchange={(e) => field.handleChange(e.target.value)}
/>
</div>
{/snippet}
</form.Field>
</div>
{:else}
No hobbies found.
{/each}
</div>
<button
type="button"
onclick={() =>
hobbiesField.pushValue({
name: '',
description: '',
yearsOfExperience: 0,
})
}
>
Add hobby
</button>
</div>
{/snippet}
</form.Field>
<form.Field name="hobbies" mode="array">
{#snippet children(hobbiesField)}
<div>
Hobbies
<div>
{#each hobbiesField.state.value as _, i}
<div>
<form.Field name={`hobbies[${i}].name`}>
{#snippet children(field)}
<div>
<label for={field.name}>Name:</label>
<input
id={field.name}
name={field.name}
value={field.state.value}
onblur={field.handleBlur}
onchange={(e) => field.handleChange(e.target.value)}
/>
<button
type="button"
onclick={() => hobbiesField.removeValue(i)}
>
X
</button>
</div>
{/snippet}
</form.Field>
<form.Field name={`hobbies[${i}].description`}>
{#snippet children(field)}
<div>
<label for={field.name}>Description:</label>
<input
id={field.name}
name={field.name}
value={field.state.value}
onblur={field.handleBlur}
onchange={(e) => field.handleChange(e.target.value)}
/>
</div>
{/snippet}
</form.Field>
</div>
{:else}
No hobbies found.
{/each}
</div>
<button
type="button"
onclick={() =>
hobbiesField.pushValue({
name: '',
description: '',
yearsOfExperience: 0,
})
}
>
Add hobby
</button>
</div>
{/snippet}
</form.Field>
These are the basic concepts and terminology used in the @tanstack/svelte-form library. Understanding these concepts will help you work more effectively with the library and create complex forms with ease.
Your weekly dose of JavaScript news. Delivered every Monday to over 100,000 devs, for free.