UNPKG

formik-validation-adaptors

Version:

A lightweight utility to integrate Zod and Joi validation with Formik.

47 lines (46 loc) 1.82 kB
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } return new (P || (P = Promise))(function (resolve, reject) { function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } step((generator = generator.apply(thisArg, _arguments || [])).next()); }); }; import { ZodError } from "zod"; import { formatValidationErrors } from "./utils.js"; /** * A Formik-compatible validation function using Zod schema. * * @param {ZodTypeAny} schema - The Zod schema used for validation * @returns A validation function that Formik can use, returning validation errors. * * @example * ```ts * const schema = z.object({ * name: z.string().min(3, "Name must be at least 3 characters 1"), * email: z.string().email("Invalid email address"), * email1: z.string().email("Invalid email address"), * }); * * const formik = useFormik({ * initialValues: { name: "", email: "" }, * validate: formikZodValidator(schema), * onSubmit: (values) => console.log(values), * }); * ``` */ const formikZodValidator = (schema) => { return (values) => __awaiter(void 0, void 0, void 0, function* () { try { yield schema.parseAsync(values); return {}; } catch (error) { if (error instanceof ZodError) return formatValidationErrors(error.errors); return {}; } }); }; export default formikZodValidator;