(fieldErrors: Record<string, string>, submittedData?: unknown) => Response
Accepts the errors returned from validator.validate
and returns a response.
The ValidatedForm
on the page will automatically receive these errors and display them.
This takes care of situations where the validation doesn't work on the client
because the user has javascript disabled.
For the vast majority of cases, your code will look like this:
const action: ActionFunction = async ({ request }) => {
const result = validator.validate(
await request.formData()
);
if (result.error) return validationError(result.error);
// do something with result.data
};
Supporting additional validations
Sometimes you might want to run some additional checks on the data beyond what the validator can do.
For example, if you have a signup form, you might want to check if a username already exists
in the database before allowing the user to be created.
In those cases, we may want to use the second argument of validationError
.
The second argument of validationError
allows you to specify
what data was used to submit the form. This is usually not necessary.
For the vast majority of cases (like in the example above),
the submitted data is already being returned as part of the response
and you don't need to do it yourself.
It's only when we start doing additional validations like this that it becomes necessary.
const action: ActionFunction = async ({ request }) => {
// We should check the correctness of the data first,
// before doing our custom check
const result = validator.validate(
await request.formData()
);
if (result.error) return validationError(result.error);
const { username } = result.data;
// The implementation of `userExistsInDatabase` will
// vary depending on your own database solution
if (await userExistsInDatabase(username)) {
return validationError(
{ username: "This username is already taken" },
result.data
);
}
// Create the user
};
The reason we need to return the submitted data is to improve user experience when javascript is disabled.
Normally, if the server returns a validation error and javascript is disabled on the client,
the form will be completely reset and the user will have to fill the whole thing out again.
By providing the submitted data, the ValidatedForm
will set the defaultValues
of the form
to be the data that was submitted. This way, the user doesn't have to fill out the form again.