form-atoms
Version:
Form primitives for Jotai
53 lines (50 loc) • 1.66 kB
text/typescript
import { Getter } from 'jotai';
import { z, ZodError } from 'zod';
import { Validate, ValidateOn } from './index.mjs';
import 'react';
import 'jotai/utils';
/**
* Validate your field atoms with Zod schemas. This function validates
* on every "user" and "submit" event, in addition to other events you specify.
*
* @param schema - Zod schema or a function that returns a Zod schema
* @param config - Configuration options
* @example
* ```ts
* const schema = z.object({
* name: z.string().min(3),
* });
*
* const nameForm = formAtom({
* name: fieldAtom({
* validate: zodValidate(schema.shape.name, {
* on: "blur",
* when: "dirty",
* })
* })
* })
* ```
*/
declare function zodValidate<Value>(schema: ((get: Getter) => z.Schema) | z.Schema, config?: ZodValidateConfig): ((state: Parameters<Exclude<Validate<Value>, undefined>>[0]) => Promise<string[] | undefined>) & {
or(config: Omit<ZodValidateConfig, "formatError">): ((state: Parameters<Exclude<Validate<Value>, undefined>>[0]) => Promise<string[] | undefined>) & any;
};
type ZodValidateConfig = {
/**
* The event or events that triggers validation.
*/
on?: ZodValidateOn | ZodValidateOn[];
/**
* Validate if the field is:
* - `touched`
* - `dirty`
*/
when?: "touched" | "dirty" | ("touched" | "dirty")[];
/**
* Format the error message returned by the validator.
*
* @param error - A ZodError object
*/
formatError?: (error: ZodError) => string[];
};
type ZodValidateOn = Exclude<ValidateOn, "user" | "submit">;
export { type ZodValidateConfig, type ZodValidateOn, zodValidate };