Skip to Content

Messages and form values

Move between protobuf-es messages and the values of a form.

A generated schema validates the init shape of a protobuf-es message. The tests of the plugin check both directions below for every fixture message and for all three outputs.

From form values to a message

Pass the output of the schema to create().

import { create } from "@bufbuild/protobuf";
import * as v from "valibot";
import { CreateUserRequestSchema } from "./gen/example/v1/user_pb";
import { CreateUserRequestValidationSchema } from "./gen/example/v1/user_pvschema";

const values = v.parse(CreateUserRequestValidationSchema, formValues);
const request = create(CreateUserRequestSchema, values);

The output type of the schema is assignable to MessageInitShape<typeof CreateUserRequestSchema>. The schema does not change the values: the message equals create(CreateUserRequestSchema, formValues).

From a message to form values

Parse the message with the schema. The schema reads the fields of the message and leaves out $typeName.

const user = await client.getUser({ id });
const defaultValues = v.parse(UserValidationSchema, user);

Use this for an edit form. The result has the input type of the schema, so it fits defaultValues in react-hook-form and TanStack Form, and initialInput in Formisch.

The type of a message is wider than the input type of the schema. A message field is optional in the message type even with required, and an enum field accepts every number. A message therefore needs the parse, or a cast, before it is a form value.

If the message breaks a rule, the parse fails. To load such a message into a form anyway, cast it and let the form show the errors.

const defaultValues = user as unknown as UserInput;

The input type

Each message has an exported input type.

import type { CreateUserRequestInput } from "./gen/example/v1/user_pvschema";

const form = useForm<CreateUserRequestInput>();

It is v.InferInput or z.input of the schema. Use it for the values of a form before validation.