formik-validation-adaptors
Version:
A lightweight utility to integrate Zod and Joi validation with Formik.
46 lines (45 loc) • 1.74 kB
JavaScript
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 { formatValidationErrors } from "./utils.js";
/**
* A Formik-compatible validation function using Joi schema.
*
* @param {Schema} schema - The Joi schema used for validation.
* @returns A validation function that Formik can use, returning validation errors.
*
* @example
* ```ts
* const schema = Joi.object({
* name: Joi.string().min(3).required(),
* email: Joi.string().email().required(),
* });
*
* const formik = useFormik({
* initialValues: { name: "", email: "" },
* validate: formikJoiValidator(schema),
* onSubmit: (values) => console.log(values),
* });
* ```
*/
const formikJoiValidator = (schema) => {
return (values) => __awaiter(void 0, void 0, void 0, function* () {
try {
const { error } = schema.validate(values, {
abortEarly: false,
allowUnknown: true,
});
return error ? formatValidationErrors(error.details) : {};
}
catch (err) {
return {};
}
});
};
export default formikJoiValidator;