UNPKG

@blocktion/json-to-table

Version:

A powerful, modular React component for converting JSON data to navigable tables with advanced features like automatic column detection, theming, and sub-table navigation. Part of the Blocktion SaaS project ecosystem.

47 lines (46 loc) 1.82 kB
import { jsx as _jsx } from "react/jsx-runtime"; import { createContext, useContext } from "react"; const ValidationContext = createContext(null); export const ValidationProvider = ({ rules, children, }) => { const validateField = (field, value, row) => { const fieldRules = rules.filter((rule) => rule.field === field); for (const rule of fieldRules) { const result = rule.validator(value, row); if (result === false || (typeof result === "string" && result.length > 0)) { return { isValid: false, error: typeof result === "string" ? result : rule.message || `Invalid ${field}`, }; } } return { isValid: true, error: null }; }; const validateRow = (row) => { const errors = {}; let isValid = true; for (const rule of rules) { const fieldValue = row?.[rule.field]; const result = rule.validator(fieldValue, row); if (result === false || (typeof result === "string" && result.length > 0)) { errors[rule.field] = typeof result === "string" ? result : rule.message || `Invalid ${rule.field}`; isValid = false; } } return { isValid, errors }; }; return (_jsx(ValidationContext.Provider, { value: { rules, validateField, validateRow }, children: children })); }; export const useValidationContext = () => { const context = useContext(ValidationContext); if (!context) { throw new Error("useValidationContext must be used within a ValidationProvider"); } return context; };