Skip to content

Usage

This library provides a set of components that can be used to build forms. Or if you prefer, you can build your own components. You must use any of these components inside the form context.

Schema

The schema is an object that contains all fields of the form. Each field must have a regular expression or a “primitive type” as value. The key of each field is the name of the field.

<script lang="ts">
import type { FieldsSchema } from '@tuentyfaiv/svelte-form';
const schema = {
name: /^[a-zA-Z]+$/,
message: "string",
accept: {
type: "boolean",
required: true,
},
} satisfies FieldsSchema;
// ... faivform function
</script>

The faivform function

Here is where the context form is created. You must use the faivform function to create a form.

This function receives a configuration object with a fields property, which is an object that receives the schema of the form. You can also pass an Adapter function instead of the schema.

<script lang="ts"> // or remove lang="ts" if you are using JS
import { faivform } from '@tuentyfaiv/svelte-form';
const form = faivform({
fields: // Schema | Adapter
});
const {
data,
loading,
errors,
styles,
setField,
setError,
check,
submit,
reset
} = $form;
// ... rest of the code
</script>
<!-- Here you can use the `Field` component inside a form element -->

Submitting a form

To submit a form, you must use the submit function and pass it to the on:submit event of the form.

<script lang="ts"> // or remove lang="ts" if you are using JS
// ... faivform function
const onSubmit = $form.submit(async (values) => {
// Do something with the values
});
</script>
<form on:submit|preventDefault={onSubmit}>
<!-- ... Built-in components or your own components -->
</form>

Built-in components

You can use the built-in components to build your forms easily. Here is an example using the Field component.

// ... faivform function
<form on:submit|preventDefault>
<Field name="name" label="Name:" />
<Field name="message" label="Leave a message:" type="textarea" />
<Field name="accept" label="Accept terms:" type="checkbox" />
<button type="submit">
Submit
</button>
</form>

Example

      

Schema

{ "name": "^[a-zA-Z]+$", "message": "string", "accept": { "type": "boolean", "required": true } }
      

Data

{ "name": null, "message": null, "accept": false }
      

Errors

{ "name": null, "message": null, "accept": null }