UNPKG

@matthew.ngo/reform

Version:

A flexible and powerful React form management library with advanced validation, state observation, and multi-group support

54 lines (51 loc) 1.59 kB
import { useMemo } from "react"; import { useDynamicValidation } from "./useDynamicValidation"; import { DynamicSchemaConfig } from "./types"; import { ReformReturn } from "../../../types"; /** * Hook wrapper for dynamic schema validation in Reform forms * * @template T - The type of form data * @param reform - Reform hook return value * @param config - Configuration for dynamic schema validation * @returns Dynamic schema validation state and methods * * @example * // Basic usage * const reform = useReform<UserForm>({...}); * const dynamicValidation = useReformDynamicValidation(reform, { * validations: [ * { * field: "email", * rules: [ * { * validate: (value) => /^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(value), * message: "Invalid email format" * } * ] * } * ] * }); * * // Validate a field * const result = dynamicValidation.validateField(0, "email", "test@example.com"); */ export const useReformDynamicValidation = <T extends Record<string, any>>( reform: ReformReturn<T>, config: DynamicSchemaConfig<T> ) => { // Memoize config to prevent unnecessary re-renders const memoizedConfig = useMemo( () => ({ validations: config.validations, getContextData: config.getContextData, }), [ // Use JSON.stringify for complex objects to compare by value JSON.stringify(config.validations), config.getContextData, ] ); // Use the optimized dynamic schema hook with memoized config return useDynamicValidation(reform, memoizedConfig); };