UNPKG

remix-validated-form

Version:

Form component and utils for easy form validation in remix

28 lines (27 loc) 994 B
import { json } from "remix"; import { formDefaultValuesKey, } from "./internal/constants"; /** * Takes the errors from a `Validator` and returns a `Response`. * When you return this from your action, `ValidatedForm` on the frontend will automatically * display the errors on the correct fields on the correct form. * * You can also provide a second argument to `validationError` * to specify how to repopulate the form when JS is disabled. * * @example * ```ts * const result = validator.validate(await request.formData()); * if (result.error) return validationError(result.error, result.submittedData); * ``` */ export function validationError(error, repopulateFields, init) { return json({ fieldErrors: error.fieldErrors, subaction: error.subaction, repopulateFields, formId: error.formId, }, { status: 422, ...init }); } export const setFormDefaults = (formId, defaultValues) => ({ [formDefaultValuesKey(formId)]: defaultValues, });