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.

Validation Library Support

There are official adapters available for zod and yup , but you can easily support whatever library you want by creating your own adapter.

And if you create an adapter for a library, feel free to make a PR to add official support 😊

Creating an adapter

Any object that conforms to the Validator type can be passed into the the ValidatedForm's validator prop.

type FieldErrors = Record<string, string>;

type ValidationResult<DataType> =
  | { data: DataType; error: undefined }
  | { error: FieldErrors; data: undefined };

type ValidateFieldResult = { error?: string };

type Validator<DataType> = {
  validate: (
    unvalidatedData: unknown
  ) => Promise<ValidationResult<DataType>>;
  validateField: (
    unvalidatedData: unknown,
    field: string
  ) => Promise<ValidateFieldResult>;
};

In order to make an adapter for your validation library of choice, you can create a function that accepts a schema from the validation library and turns it into a validator.

Note the use of createValidator. It takes care of unflattening the data for nested objects and arrays since the form doesn't know anything about object and arrays and this should be handled by the adapter. For more on this you can check the implementations for withZod and withYup.

The out-of-the-box support for yup in this library works like this:

export const withYup = <Schema extends AnyObjectSchema>(
  validationSchema: Schema
  // For best result with Typescript,
  // we should type the `Validator`
  // we return based on the provided schema
): Validator<InferType<Schema>> =>
  createValidator({
    validate: async (unvalidatedData) => {
      // Validate with yup and return the
      // validated & typed data or the error

      if (isValid)
        return {
          data: { field1: "someValue" },
          error: undefined,
        };
      else
        return {
          error: { field1: "Some error!" },
          data: undefined,
        };
    },
    validateField: async (unvalidatedData, field) => {
      // Validate the specific field with yup

      if (isValid) return { error: undefined };
      else return { error: "Some error" };
    },
  });