Skip to Content

Formisch

Build a Formisch form from a generated Valibot schema.

Formisch builds a form from a Valibot schema. Pass the output of lib=valibot to useForm.

The repository has a complete form in examples/react-forms/src/forms/FormischForm.tsx.

Form

import { Field, Form, useForm } from "@formisch/react";
import { create } from "@bufbuild/protobuf";
import { CreateUserRequestSchema } from "./gen/example/v1/user_pb";
import { CreateUserRequestValidationSchema } from "./gen/example/v1/user_pvschema";

const form = useForm({
  schema: CreateUserRequestValidationSchema,
  initialInput: { name: "", email: "", tags: [], points: 0n, contact: { case: undefined } },
});

<Form of={form} onSubmit={(output) => send(create(CreateUserRequestSchema, output))}>
  <Field of={form} path={["name"]}>
    {(field) => (
      <>
        <input {...field.props} value={field.input ?? ""} />
        <p role="alert">{field.errors?.[0]}</p>
      </>
    )}
  </Field>
</Form>;

onSubmit receives the output of the schema, which is the init shape of the message. initialInput is a partial value, so it needs no cast.

Fields that are not strings

field.props reads the string of the element. For a number, a bigint, or a list, use a controlled input and call field.onChange with the converted value.

<Field of={form} path={["points"]}>
  {(field) => (
    <input
      inputMode="numeric"
      value={String(field.input ?? "")}
      onChange={(event) => {
        if (isIntegerText(event.target.value)) {
          field.onChange(parseOptionalBigInt(event.target.value));
        }
      }}
    />
  )}
</Field>

oneof

Use the paths ["contact", "case"] and ["contact", "value"]. To change the case, replace the whole oneof with setInput.

setInput(form, { path: ["contact"], input: { case: "phone", value: "" } });

Languages

Formisch validates with Valibot, so the Valibot language setting applies. After a language switch, validate a submitted form again.

useEffect(() => {
  if (form.isSubmitted) {
    void validate(form);
  }
}, [lang, form]);