Created
January 24, 2024 18:49
-
-
Save vixeven/e77ceceb90d585db75cd21c88c0e29a9 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import { BaseSchema, parseAsync, ParseInfo, ValiError } from "valibot"; | |
export class ValidationError extends Error { | |
public name = "ValidationError"; | |
public inner: Array<{ path: string; message: string }> = []; | |
public constructor(message: string) { | |
super(message); | |
} | |
} | |
function createValidationError(e: ValiError) { | |
const error = new ValidationError(e.message); | |
error.inner = e.issues.map((issue) => ({ | |
message: issue.message, | |
path: issue.path.map((path) => path.key).join("."), | |
})); | |
return error; | |
} | |
type ValibotSchema = BaseSchema; | |
export function valibotToFormikValidationSchema<T>( | |
schema: ValibotSchema, | |
schemaOptions: Pick< | |
ParseInfo, | |
"abortEarly" | "abortPipeEarly" | "skipPipe" | |
> = {} | |
): { validate: (values: T) => Promise<void> } { | |
return { | |
async validate(values: T) { | |
try { | |
const schemaOpts = { | |
abortEarly: false, | |
abortPipeEarly: false, | |
...schemaOptions, | |
}; | |
await parseAsync(schema, values, schemaOpts); | |
} catch (error) { | |
if (error instanceof ValiError) { | |
throw createValidationError(error); | |
} | |
throw error; | |
} | |
}, | |
}; | |
} | |
/** | |
* Example of usage: | |
* | |
* ```tsx | |
* import * as v from "valibot"; | |
* | |
* const schema = v.object({ | |
* name: v.string(), | |
* age: v.number(), | |
* }); | |
* | |
* const formikSchema = toFormikValidationSchema(schema); | |
* | |
* <Formik validationSchema={formikSchema} /> | |
* ``` | |
*/ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment