Remix Validated Form

RVF v6 has been released!

For new projects, we recommend starting with v6. For existing projects, there's a migration guide available.

(formId: string, defaultValues: any) => FormDefaults

Automatically set the default values of a form from your loader.

Basic Usage

To use this, the ValidatedForm must have an id.

import { json, DataFunctionArgs } from "@remix-run/node";
import { setFormDefaults } from "remix-validated-form";

export const loader = (args: DataFunctionArgs) => {
  return json(
    setFormDefaults("myForm", {
      firstName: "John",
      lastName: "Doe",
    }),
  );
};

export default function MyForm() {
  return (
    <ValidatedForm id="myForm">
      Required props and form elements omitted for brevity
    </ValidatedForm>
  );
}

Note: This does not return a response like validationError does. Instead, it returns data that's meant to be included in remix's own json response.

Usage with other loader data

Often, you'll want to include other data in your loader's response. You can do that like this:

import { json, DataFunctionArgs } from "@remix-run/node";
import {
  setFormDefaults,
  FormDefaults,
} from "remix-validated-form";

type LoaderData = { message: string };

export const loader = (args: DataFunctionArgs) => {
  return json<LoaderData & FormDefaults>({
    message: "Hello World!",
    ...setFormDefaults("myForm", {
      firstName: "John",
      lastName: "Doe",
    }),
  });
};

Setting multiple forms at once

You can also set the default values for multiple forms at once

import { json, DataFunctionArgs } from "@remix-run/node";
import {
  setFormDefaults,
  FormDefaults,
} from "remix-validated-form";

export const loader = (args: DataFunctionArgs) => {
  return json<FormDefaults>({
    ...setFormDefaults("myForm", {
      firstName: "John",
      lastName: "Doe",
    }),
    ...setFormDefaults("myOtherForm", {
      favoriteFood: "Pizza",
    }),
  });
};

Order of precedence

It's possible to have default values set in multiple places.