@explita/daily-toolset-form
Version:
A lightweight form toolkit for React built with developer ergonomics in mind. Includes a flexible Form component, useForm, useField, and useFormContext hooks for managing form state and validation with ease. Designed to simplify complex forms while remain
59 lines (58 loc) • 2.31 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", { value: true });
exports.validateForm = validateForm;
exports.extractFieldErrors = extractFieldErrors;
/**
* Validates form data against a Zod schema.
*
* @param {Schema} validationSchema - The Zod schema to validate the form data against.
* @param {FormData | Record<string, unknown> | undefined} formData - The form data to validate.
* @returns {Promise<ValidationResponse<z.infer<Schema>>>} - A promise that resolves to a validation response.
*
* @throws {Error} Throws an error if a valid Zod schema or valid FormData is not provided,
* or if an unexpected error occurs during validation.
*/
async function validateForm(validationSchema, formData) {
if (typeof (validationSchema === null || validationSchema === void 0 ? void 0 : validationSchema.safeParseAsync) !== "function") {
throw new Error("A valid Zod schema is required for form validation. Please provide a valid Zod schema and try again.");
}
if (!formData) {
throw new Error("A valid FormData object is required for form validation. Please provide a valid FormData object and try again.");
}
try {
let form = formData;
if (formData instanceof FormData) {
form = Object.fromEntries(formData.entries());
}
const result = await validationSchema.safeParseAsync(form);
if (result.success) {
return {
success: true,
data: result.data,
};
}
const errors = extractFieldErrors(result.error, validationSchema);
return {
success: false,
errors,
message: "Validation failed",
data: form,
};
}
catch (error) {
throw new Error(`Validation failed due to an unexpected error: ${error.message || "Please make sure Zod is installed and try again."}`);
}
}
function extractFieldErrors(error, schema) {
const fieldErrors = {};
for (const { path, message } of error.issues) {
if (path.length > 0) {
const key = path[0];
// Avoid overwriting if error for key already added
if (!fieldErrors[key]) {
fieldErrors[key] = message;
}
}
}
return fieldErrors;
}