formik-validator-zod
Version:
Helper to simplify validating Formik values with Zod
27 lines (26 loc) • 933 B
JavaScript
;
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.withZodSchema = void 0;
const deepmerge_1 = __importDefault(require("deepmerge"));
/**
* Allows you to easily use Zod schemas with the <Formik /> component `validate`
* prop.
*
* ```js
* <Formik {...} validate={withZodSchema(yourSchema)}>
* ```
*/
const withZodSchema = (schema, params) => (values) => {
const result = schema.safeParse(values, params);
if (result.success)
return {};
return result.error.issues.reduce((acc, curr) => {
return (0, deepmerge_1.default)(acc, curr.path.reduceRight((errors, pathSegment) => ({
[pathSegment]: !Object.keys(errors).length ? curr.message : errors,
}), {}));
}, {});
};
exports.withZodSchema = withZodSchema;