Back to Shark UI

Formisch

docs/forms/formisch

latest25.2 KB
Original Source

Sections

Components

Utilities

Forms

Hooks

Formisch

Copy Markdown

Build forms in React using Formisch and Valibot.

DocsAPI

This guide will cover building forms using the Field component, adding schema validation with Valibot, handling errors, ensuring accessibility, and more.

Demo#

We’ll build a form with a text input and textarea. When you submit, the form data is validated and any errors will be shown.

Browser validation disabled

For the purposes of this demo, browser validation is disabled to illustrate schema validation. In production, keep native validation enabled when appropriate.

PreviewCode

Bug Report

Help us improve by reporting bugs you encounter.

Bug Title

Description

0/100 characters

Include steps to reproduce, expected behavior, and what actually happened.

ResetSubmit

Approach#

This form uses Formisch for state and Valibot for validation. We'll build forms using the Field component, which gives you complete flexibility over the markup and styling.

  • Uses Formisch's useForm hook for form state management.
  • Uses the Form component for submit handling.
  • Import Formisch’s Field under an alias (FormischField) for controlled inputs.
  • Uses Shark Field components for building accessible forms.
  • Uses client-side validation by passing your Valibot schema into schema.

Anatomy#

Typical structure: wrap each field with FormischField, and the Field component.

<Form of={form} onSubmit={onSubmit}>
  <FieldGroup>
    <FormischField of={form} path={["title"]}>
      {(field) => (
        <Field invalid={Boolean(field.errors?.length)}>
          <FieldLabel>Bug Title</FieldLabel>
          <Input {...field.props} value={field.input} />
           <FieldDescription>
            Provide a concise title for your bug report.
          </FieldDescription>
          <FieldError>{field.errors?.[0]}</FieldError>
        </Field>
      )}
    </FormischField>
  </FieldGroup>
  <Button type="submit">Submit</Button>
</Form>

Form#

Create a schema#

Define your form shape with a Valibot schema.

Note: Formisch only supports Valibot for validation.

Expand

import * as v from "valibot";

export const bugReportSchema = v.object({
  title: v.pipe(
    v.string(),
    v.minLength(5, "Bug title must be at least 5 characters."),
    v.maxLength(32, "Bug title must be at most 32 characters.")
  ),
  description: v.pipe(
    v.string(),
    v.minLength(20, "Description must be at least 20 characters."),
    v.maxLength(100, "Description must be at most 100 characters.")
  ),
});

Expand

Setup#

  • Create the form with useForm from Formisch and pass your schema to the schema option,
  • Wrap fields in Form and pass the form to the onSubmit option.

form.tsx

import { Form, Field as FormischField, useForm } from "@formisch/react";
import * as v from "valibot";

const formSchema = v.object({
  // ...
});

export const BugReportForm = () => {
  const form = useForm({
    schema: formSchema,
    initialInput: {
      title: "",
      description: "",
    },
  });

  return (
    <Form of={form} onSubmit={(output) => console.log(output)}>
    </Form>
  );
};

Build#

Build the form using the FormischField from Formisch and the Shark Field.

Expand

"use client";

import {
  Form,
  Field as FormischField,
  reset,
  type SubmitHandler,
  useForm,
} from "@formisch/react";
import { toast } from "@registry/react/components/toast";
import * as v from "valibot";
import { Button } from "@/components/ui/button";
import {
  Card,
  CardContent,
  CardFooter,
  CardHeader,
} from "@/components/ui/card";
import {
  Field,
  FieldDescription,
  FieldError,
  FieldGroup,
  FieldLabel,
} from "@/components/ui/field";
import { Input } from "@/components/ui/input";
import {
  InputGroup,
  InputGroupAddon,
  InputGroupText,
  InputGroupTextarea,
} from "@/components/ui/input-group";

const formSchema = v.object({
  title: v.pipe(
    v.string(),
    v.minLength(5, "Bug title must be at least 5 characters."),
    v.maxLength(32, "Bug title must be at most 32 characters.")
  ),
  description: v.pipe(
    v.string(),
    v.minLength(20, "Description must be at least 20 characters."),
    v.maxLength(100, "Description must be at most 100 characters.")
  ),
});

export const BugReportForm = () => {
  const form = useForm({
    schema: formSchema,
    initialInput: {
      title: "",
      description: "",
    },
  });

  const onSubmit: SubmitHandler<typeof formSchema> = (output) => {
    toast.info({
      id: "bug-report-submitted",
      title: "Bug submitted",
      description: (
        <pre className="mt-2">
          <code>{JSON.stringify(output, null, 2)}</code>
        </pre>
      ),
    });
  };

  return (
    <Card asChild className="w-full sm:max-w-md">
      <Form of={form} onSubmit={onSubmit}>
        <CardHeader
          description="Help us improve by reporting bugs you encounter."
          title="Bug Report"
        />
        <CardContent>
          <FieldGroup>
            <FormischField of={form} path={["title"]}>
              {(field) => (
                <Field invalid={Boolean(field.errors?.length)}>
                  <FieldLabel>Bug Title</FieldLabel>
                  <Input
                    {...field.props}
                    autoComplete="off"
                    placeholder="Login button not working on mobile"
                    value={field.input}
                  />
                  <FieldError>{field.errors?.[0]}</FieldError>
                </Field>
              )}
            </FormischField>
            <FormischField of={form} path={["description"]}>
              {(field) => (
                <Field invalid={Boolean(field.errors?.length)}>
                  <FieldLabel>Description</FieldLabel>
                  <InputGroup>
                    <InputGroupTextarea
                      {...field.props}
                      className="min-h-24 resize-none"
                      placeholder="I'm having an issue with the login button on mobile."
                      rows={6}
                      value={field.input}
                    />
                    <InputGroupAddon align="block-end">
                      <InputGroupText className="tabular-nums">
                        {field.input?.length}/100 characters
                      </InputGroupText>
                    </InputGroupAddon>
                  </InputGroup>
                  <FieldDescription>
                    Include steps to reproduce, expected behavior, and what
                    actually happened.
                  </FieldDescription>
                  <FieldError>{field.errors?.[0]}</FieldError>
                </Field>
              )}
            </FormischField>
          </FieldGroup>
        </CardContent>
        <CardFooter>
          <Button onClick={() => reset(form)} variant="outline">
            Reset
          </Button>
          <Button type="submit">Submit</Button>
        </CardFooter>
      </Form>
    </Card>
  );
};

Expand

Done#

That's it. You now have a fully accessible form with client-side validation.

When you submit the form, the onSubmit handler on Form receives validated output. If the form data is invalid, Formisch will display the errors on field.errors for FieldError.

Validation#

Client-side#

Formisch validates your form data using the Valibot schema. Define a schema and pass it to the schema option of the useForm hook.

example-form.tsx

import { useForm } from "@formisch/react"
import * as v from "valibot"

const formSchema = v.object({
  title: v.string(),
  description: v.optional(v.string()),
})

export const ExampleForm = () => {
  const form = useForm({
    schema: formSchema,
    initialInput: {
      title: "",
      description: "",
    },
  })
}

Modes#

Configure when validation runs via the validate and revalidate options:

form.tsx

const form = useForm({
  schema: formSchema,
  validate: "submit",
  revalidate: "input",
})
OptionRole
"initial"Validation triggers on initial render.
"touch"Validation triggers on field touch.
"input"Validation triggers on field input.
"change"Validation triggers on field change.
"blur"Validation triggers on field blur.
"submit"Validation triggers on form submit.

Displaying Errors#

Display errors next to the field using FieldError. For styling and accessibility:

  • Add the invalid prop to the Field component.
  • Don't need to add the invalid prop to the form control such as Input, Checkbox, etc.

form.tsx

<FormischField of={form} path={["email"]}>
  {(field) => (
    <Field invalid={Boolean(field.errors?.length)}>
      <FieldLabel>Email</FieldLabel>
      <Input {...field.props} type="email" value={field.input} />
      <FieldError>{field.errors?.[0]}</FieldError>
    </Field>
  )}
</FormischField>

Different types of fields#

Input#

  • Spread field.props on Input and set value={field.input}.
  • Add the invalid prop to the Field component and pass the error message to the FieldError component.

PreviewCode

Profile Settings

Update your profile information below.

Username

This is your public display name. Must be between 3 and 10 characters. Must only contain letters, numbers, and underscores.

ResetSave

Textarea#

  • Spread field.props on Textarea and set value={field.input}.
  • Add the invalid prop to the Field component and pass the error message to the FieldError component.

PreviewCode

Personalization

Customize your experience by telling us more about yourself.

More about you

Tell us more about yourself. This will be used to help us personalize your experience.

ResetSave

NativeSelect#

  • Spread field.props on NativeSelect and set value={field.input}.
  • Add the invalid prop to the Field component and pass the error message to the FieldError component.

PreviewCode

Language Preferences

Select your preferred spoken language.

Spoken Language

For best results, select the language you speak.

AutoEnglishSpanishFrenchGermanItalianChineseJapanese

ResetSave

Select#

  • Wire field.input and field.onChange to Select.
  • Add the invalid prop to the Field component and pass the error message to the FieldError component.

PreviewCode

Language Preferences

Select your preferred spoken language.

Spoken Language

For best results, select the language you speak.

Select

AutoEnglishSpanishFrenchGermanItalianChineseJapanese

ResetSave

Checkbox#

  • Wire field.input and field.onChange to Checkbox.
  • Add the invalid prop to the Field component and pass the error message to the FieldError component.
  • Remember to add data-slot="checkbox-group" to the FieldGroup component for proper styling and spacing.

PreviewCode

Notifications

Manage your notification preferences.

Responses

Get notified for requests that take time, like research or image generation.

Push notifications

Tasks

Get notified when tasks you've created have updates.

Push notifications

Email notifications

ResetSave

Radio group#

  • Wire field.input and field.onChange to RadioGroup.
  • Add the invalid prop to the Field component and pass the error message to the FieldError component.

PreviewCode

Subscription Plan

See pricing and features for each plan.

Plan

You can upgrade or downgrade your plan at any time.

Starter (100K tokens/month)

For everyday use with basic features.

Pro (1M tokens/month)

For advanced AI usage with more features.

Enterprise (Unlimited tokens)

For large teams and heavy usage.

ResetSave

Switch#

  • Wire field.input and field.onChange to Switch.
  • Add the invalid prop to the Field component and pass the error message to the FieldError component.

PreviewCode

Security Settings

Manage your account security preferences.

Multi-factor authentication

Enable multi-factor authentication to secure your account.

ResetSave

NumberInput#

  • Wire field.input and field.onChange to NumberInput.
  • Add the invalid prop to the Field component and pass the error message to the FieldError component.

PreviewCode

Salary expectations

Share your target gross annual salary in EUR.

Expected annual salary

EUR

ResetSave

Slider#

  • Wire field.input and field.onChange to Slider.
  • Add the invalid prop to the Field component and pass the error message to the FieldError component.

PreviewCode

Listings filter

Set a price range so we only show results in your budget.

Price range$0 - $10000

Drag each thumb to set the lower and upper bound.

ResetApply

Combobox#

  • Wire field.input and field.onChange to Combobox.
  • Add the invalid prop to the Field component and pass the error message to the FieldError component.

PreviewCode

Role setup

Tell us which team you work with most so we can tailor workflows.

Primary department

Type to filter the list, then pick one option.

ResetSave

Autocomplete#

  • Wire field.input and field.onChange to Autocomplete.
  • Add the invalid prop to the Field component and pass the error message to the FieldError component.

PreviewCode

Tech stack

Select the technology you're most familiar with.

Primary technology

Type to filter the list, then pick one option.

ResetSave

Date Picker#

  • Wire field.input and field.onChange to DatePicker.
  • Add the invalid prop to the Field component and pass the error message to the FieldError component.

PreviewCode

Scheduling

Pick a day that works for a first-round interview. We will confirm by email.

Preferred interview date

Pick a date

ResetSave

Input OTP#

  • Wire field.input and field.onChange to InputOTP.
  • Add the invalid prop to the Field component and pass the error message to the FieldError component.

PreviewCode

Account recovery

Enter one of your single-use backup codes if you cannot access your authenticator app.

Backup code

Codes can only be used once.

ResetSave

Rating#

  • Use field.onChange with Rating’s onValueChange and bind value from field.input.
  • Add the invalid prop to the Field component and pass the error message to the FieldError component.

PreviewCode

Quick feedback

Help us improve by sharing how likely you are to recommend Shark UI to a colleague.

How useful is this project?

1 = not likely, 5 = very likely.

ResetSave

File Upload#

  • Use FileUpload onFileAccept to push files into the field value (field.onChange).
  • Add the invalid prop to the Field component and pass the error message to the FieldError component.

PreviewCode

Application materials

Upload your résumé or CV.

Résumé

Accepted formats: PDF and Word documents.

ResetSave

Complex Forms#

Here is an example of a more complex form with multiple fields and validation.

PreviewCode

You're almost there!

Choose your subscription plan and billing period.

Subscription plan

Choose your subscription plan.

Basic

For individuals and small teams

Pro

For businesses with higher demands

Billing period

Select

MonthlyYearly

Choose how often you want to be billed.

Add-ons

Select additional features you'd like to include.

Analytics

Advanced analytics and reporting

Backup

Automated daily backups

Priority Support

24/7 premium customer support

Email notifications

Receive email updates about your subscription.

Save preferencesReset

Resetting the Form#

Import reset and pass the form to reset the form to its default values.

import { reset } from "@formisch/react";

<Button
  type="button"
  variant="outline"
  onClick={() => reset(form)}
>
  Reset
</Button>

Array Fields#

Formisch provides a FieldArray component for managing dynamic array fields. Also provides helpers like insert and remove for dynamic lists. This is useful when you need to add or remove fields dynamically.

PreviewCode

Contact emails

Manage your contact email addresses.

Email addresses

Add up to 5 email addresses where we can contact you.

Add email address

ResetSave

Array Field Structure#

Use FieldArray component and pass the form to the of prop.

form.tsx

import { FieldArray, Field as FormischField, useForm } from "@formisch/react";

export const ExampleForm = () => {
  const form = useForm({
    // ... form config
  });

  return (
    <FieldArray of={form} path={["emails"]}>
      {(arrayField) => (
        arrayField.items.map((itemId, index) => (
          // Nested field for each array item
        ))
      )}
    </FieldArray>
  );
}

Nested Fields#

Use arrayField.items to render each nested field, passing the correct path for each item.

form.tsx

{
  arrayField.items.map((itemId, index) => (
    <FormischField 
      key={itemId} 
      of={form} 
      path={["emails", index, "contact", "address"]}
    >
      {(field) => (
        <Field invalid={Boolean(field.errors?.length)} orientation="horizontal">
          <FieldContent>
            <InputGroup>
              <InputGroupInput
                {...field.props}
                autoComplete="email"
                onChange={(e) => field.onChange(e.target.value)}
                placeholder="[email protected]"
                type="email"
                value={field.input}
              />
              {arrayField.items.length > 1 && (
                <InputGroupAddon align="inline-end">
                  <InputGroupButton
                    aria-label={`Remove email ${String(index + 1)}`}
                    onClick={() =>
                      remove(form, { path: ["emails"], at: index })
                    }
                    size="icon-xs"
                    type="button"
                    variant="ghost"
                  >
                    <XIcon aria-hidden className="size-4" />
                  </InputGroupButton>
                </InputGroupAddon>
              )}
            </InputGroup>
            <FieldError>{field.errors?.[0]}</FieldError>
          </FieldContent>
        </Field>
      )}
    </FormischField>
  ))
}

Adding items#

  • Use insert to add a new array item.
  • Provide initialInput matching the nested structure of the array element.

form.tsx

import { insert } from "@formisch/react";

<Button
  type="button"
  variant="outline"
  size="sm"
  onClick={() =>
    insert(form, {
      path: ["emails"],
      initialInput: { contact: { address: "" } },
    })
  }
  disabled={arrayField.items.length >= 5}
>
  Add Email Address
</Button>

Removing items#

Use remove with the array path and index.

form.tsx

import { remove } from "@formisch/react";

{
  arrayField.items.length > 1 && (
    <InputGroupAddon align="inline-end">
      <InputGroupButton
        type="button"
        variant="ghost"
        size="icon-xs"
        onClick={() => remove(form, { path: ["emails"], at: index })}
        aria-label={`Remove email ${index + 1}`}
      >
        <XIcon />
      </InputGroupButton>
    </InputGroupAddon>
  );
}

Array validation#

Use Valibot's array method to validate array fields.

form.tsx

import * as v from "valibot";

const formSchema = v.object({
  emails: v.pipe(
    v.array(
      v.object({
        contact: v.object({
          address: v.pipe(
            v.string(),
            v.nonEmpty("Enter an email address."),
            v.email("Enter a valid email address.")
          ),
        }),
      })
    ),
    v.minLength(1, "Add at least one email address."),
    v.maxLength(5, "You can add up to 5 email addresses.")
  ),
});

[

Previous page

Swap ](/docs/utilities/swap)[

Next page

React Hook Form ](/docs/forms/react-hook-form)

On This Page

DemoApproachAnatomyFormCreate a schemaSetupBuildDoneValidationClient-sideModesDisplaying ErrorsDifferent types of fieldsInputTextareaNativeSelectSelectCheckboxRadio groupSwitchNumberInputSliderComboboxAutocompleteDate PickerInput OTPRatingFile UploadComplex FormsResetting the FormArray FieldsArray Field StructureNested FieldsAdding itemsRemoving itemsArray validation