ValidatedForm
Props
Validator<DataType>
A Validator
object that describes how to validate the form.
The generic type DataType
is the type of the data that the form is expecting.
If you provide an onSubmit
prop to the ValidatedForm
,
it will be called with the form data and be correctly typed as DataType
.
const validator = withZod(z.object({ name: z.string() }));
<ValidatedForm validator={validator} />;
Partial<DataType>Optional
An object to be used for the default values of the form fields.
booleanOptional
Reset the form to the default values after the form has been successfully submitted. This is useful if you want to submit the same form multiple times, and don't redirect in between submissions.
stringOptional
Allows you to specify a "subaction" for the form. This adds a hidden input to the form with the value of the subaction. The purpose of this is to allow you to handle multiple forms in the same action function.
export const action: ActionFunction = async ({
request,
}) => {
const data = await request.formData();
// This will be `form1` or `form2`
// depending on which form you submitted
const subaction = data.get("subaction");
// etc
};
export default function MyPage() {
return (
<>
<ValidatedForm
validator={validator}
subaction="form1"
method="post"
>
<MyInput name="name" />
<SubmitButton />
</ValidatedForm>
<ValidatedForm
validator={validator}
subaction="form2"
method="post"
>
<MyInput name="something" />
<SubmitButton />
</ValidatedForm>
</>
);
}
(data: DataType, event: React.FormEvent<HTMLFormElement>) => voidOptional
A submit callback that gets called when the form is submitted.
The data
argument is the parsed and typed form data.
const validator = withZod(z.object({ name: z.string() }));
<ValidatedForm
validator={vaidator}
onSubmit={(data) => {
// Data is an object with a `name` property
// of type `string` because of the validator above.
console.log(data.name);
}}
/>;
React.RefObject<HTMLFormElement>Optional
A ref to the underlying form element. This is used instead of forwardRef
because of the generic type of the component.
(data: DataType, event: React.FormEvent<HTMLFormElement>) => voidOptional
Allows you to provide a fetcher
from remix's useFetcher
hook.
The form will use the fetcher for loading states, action data, etc
instead of the default form action. This can be useful for when you need to
submit the form programatically but still have validation errors show up.
booleanOptional
Normally, the first invalid input will be focused when the validation fails on form submit.
Set this to false
to disable this behavior.