build revisions and layout updates for toast

This commit is contained in:
makearmy 2025-09-26 14:31:18 -04:00
parent b341a3675e
commit 39235193e6
1116 changed files with 130517 additions and 12 deletions

View file

@ -1,19 +1,25 @@
import './styles/globals.css'
// app/layout.tsx
import type { Metadata } from "next";
import "./globals.css";
import { Toaster } from "@/components/ui/toaster";
export const metadata = {
title: 'LE-DB',
description: 'Laser Everything Community Database',
}
export const metadata: Metadata = {
title: "MakeArmy",
description: "Laser tooling & community utilities",
};
export default function RootLayout({
children,
}: {
children: React.ReactNode
children: React.ReactNode;
}) {
return (
<html lang="en" className="dark">
<body>{children}</body>
<html lang="en" suppressHydrationWarning>
<body className="min-h-screen bg-background text-foreground antialiased">
{children}
{/* Shadcn toast portal */}
<Toaster />
</body>
</html>
)
);
}

36
components/ui/badge.tsx Normal file
View file

@ -0,0 +1,36 @@
import * as React from "react"
import { cva, type VariantProps } from "class-variance-authority"
import { cn } from "@/lib/utils"
const badgeVariants = cva(
"inline-flex items-center rounded-full border px-2.5 py-0.5 text-xs font-semibold transition-colors focus:outline-none focus:ring-2 focus:ring-ring focus:ring-offset-2",
{
variants: {
variant: {
default:
"border-transparent bg-primary text-primary-foreground hover:bg-primary/80",
secondary:
"border-transparent bg-secondary text-secondary-foreground hover:bg-secondary/80",
destructive:
"border-transparent bg-destructive text-destructive-foreground hover:bg-destructive/80",
outline: "text-foreground",
},
},
defaultVariants: {
variant: "default",
},
}
)
export interface BadgeProps
extends React.HTMLAttributes<HTMLDivElement>,
VariantProps<typeof badgeVariants> {}
function Badge({ className, variant, ...props }: BadgeProps) {
return (
<div className={cn(badgeVariants({ variant }), className)} {...props} />
)
}
export { Badge, badgeVariants }

View file

@ -0,0 +1,22 @@
import * as React from "react"
import { cn } from "@/lib/utils"
const Textarea = React.forwardRef<
HTMLTextAreaElement,
React.ComponentProps<"textarea">
>(({ className, ...props }, ref) => {
return (
<textarea
className={cn(
"flex min-h-[80px] w-full rounded-md border border-input bg-background px-3 py-2 text-base ring-offset-background placeholder:text-muted-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:cursor-not-allowed disabled:opacity-50 md:text-sm",
className
)}
ref={ref}
{...props}
/>
)
})
Textarea.displayName = "Textarea"
export { Textarea }

129
components/ui/toast.tsx Normal file
View file

@ -0,0 +1,129 @@
"use client"
import * as React from "react"
import * as ToastPrimitives from "@radix-ui/react-toast"
import { cva, type VariantProps } from "class-variance-authority"
import { X } from "lucide-react"
import { cn } from "@/lib/utils"
const ToastProvider = ToastPrimitives.Provider
const ToastViewport = React.forwardRef<
React.ElementRef<typeof ToastPrimitives.Viewport>,
React.ComponentPropsWithoutRef<typeof ToastPrimitives.Viewport>
>(({ className, ...props }, ref) => (
<ToastPrimitives.Viewport
ref={ref}
className={cn(
"fixed top-0 z-[100] flex max-h-screen w-full flex-col-reverse p-4 sm:bottom-0 sm:right-0 sm:top-auto sm:flex-col md:max-w-[420px]",
className
)}
{...props}
/>
))
ToastViewport.displayName = ToastPrimitives.Viewport.displayName
const toastVariants = cva(
"group pointer-events-auto relative flex w-full items-center justify-between space-x-4 overflow-hidden rounded-md border p-6 pr-8 shadow-lg transition-all data-[swipe=cancel]:translate-x-0 data-[swipe=end]:translate-x-[var(--radix-toast-swipe-end-x)] data-[swipe=move]:translate-x-[var(--radix-toast-swipe-move-x)] data-[swipe=move]:transition-none data-[state=open]:animate-in data-[state=closed]:animate-out data-[swipe=end]:animate-out data-[state=closed]:fade-out-80 data-[state=closed]:slide-out-to-right-full data-[state=open]:slide-in-from-top-full data-[state=open]:sm:slide-in-from-bottom-full",
{
variants: {
variant: {
default: "border bg-background text-foreground",
destructive:
"destructive group border-destructive bg-destructive text-destructive-foreground",
},
},
defaultVariants: {
variant: "default",
},
}
)
const Toast = React.forwardRef<
React.ElementRef<typeof ToastPrimitives.Root>,
React.ComponentPropsWithoutRef<typeof ToastPrimitives.Root> &
VariantProps<typeof toastVariants>
>(({ className, variant, ...props }, ref) => {
return (
<ToastPrimitives.Root
ref={ref}
className={cn(toastVariants({ variant }), className)}
{...props}
/>
)
})
Toast.displayName = ToastPrimitives.Root.displayName
const ToastAction = React.forwardRef<
React.ElementRef<typeof ToastPrimitives.Action>,
React.ComponentPropsWithoutRef<typeof ToastPrimitives.Action>
>(({ className, ...props }, ref) => (
<ToastPrimitives.Action
ref={ref}
className={cn(
"inline-flex h-8 shrink-0 items-center justify-center rounded-md border bg-transparent px-3 text-sm font-medium ring-offset-background transition-colors hover:bg-secondary focus:outline-none focus:ring-2 focus:ring-ring focus:ring-offset-2 disabled:pointer-events-none disabled:opacity-50 group-[.destructive]:border-muted/40 group-[.destructive]:hover:border-destructive/30 group-[.destructive]:hover:bg-destructive group-[.destructive]:hover:text-destructive-foreground group-[.destructive]:focus:ring-destructive",
className
)}
{...props}
/>
))
ToastAction.displayName = ToastPrimitives.Action.displayName
const ToastClose = React.forwardRef<
React.ElementRef<typeof ToastPrimitives.Close>,
React.ComponentPropsWithoutRef<typeof ToastPrimitives.Close>
>(({ className, ...props }, ref) => (
<ToastPrimitives.Close
ref={ref}
className={cn(
"absolute right-2 top-2 rounded-md p-1 text-foreground/50 opacity-0 transition-opacity hover:text-foreground focus:opacity-100 focus:outline-none focus:ring-2 group-hover:opacity-100 group-[.destructive]:text-red-300 group-[.destructive]:hover:text-red-50 group-[.destructive]:focus:ring-red-400 group-[.destructive]:focus:ring-offset-red-600",
className
)}
toast-close=""
{...props}
>
<X className="h-4 w-4" />
</ToastPrimitives.Close>
))
ToastClose.displayName = ToastPrimitives.Close.displayName
const ToastTitle = React.forwardRef<
React.ElementRef<typeof ToastPrimitives.Title>,
React.ComponentPropsWithoutRef<typeof ToastPrimitives.Title>
>(({ className, ...props }, ref) => (
<ToastPrimitives.Title
ref={ref}
className={cn("text-sm font-semibold", className)}
{...props}
/>
))
ToastTitle.displayName = ToastPrimitives.Title.displayName
const ToastDescription = React.forwardRef<
React.ElementRef<typeof ToastPrimitives.Description>,
React.ComponentPropsWithoutRef<typeof ToastPrimitives.Description>
>(({ className, ...props }, ref) => (
<ToastPrimitives.Description
ref={ref}
className={cn("text-sm opacity-90", className)}
{...props}
/>
))
ToastDescription.displayName = ToastPrimitives.Description.displayName
type ToastProps = React.ComponentPropsWithoutRef<typeof Toast>
type ToastActionElement = React.ReactElement<typeof ToastAction>
export {
type ToastProps,
type ToastActionElement,
ToastProvider,
ToastViewport,
Toast,
ToastTitle,
ToastDescription,
ToastClose,
ToastAction,
}

35
components/ui/toaster.tsx Normal file
View file

@ -0,0 +1,35 @@
"use client"
import { useToast } from "@/hooks/use-toast"
import {
Toast,
ToastClose,
ToastDescription,
ToastProvider,
ToastTitle,
ToastViewport,
} from "@/components/ui/toast"
export function Toaster() {
const { toasts } = useToast()
return (
<ToastProvider>
{toasts.map(function ({ id, title, description, action, ...props }) {
return (
<Toast key={id} {...props}>
<div className="grid gap-1">
{title && <ToastTitle>{title}</ToastTitle>}
{description && (
<ToastDescription>{description}</ToastDescription>
)}
</div>
{action}
<ToastClose />
</Toast>
)
})}
<ToastViewport />
</ToastProvider>
)
}

194
hooks/use-toast.ts Normal file
View file

@ -0,0 +1,194 @@
"use client"
// Inspired by react-hot-toast library
import * as React from "react"
import type {
ToastActionElement,
ToastProps,
} from "@/components/ui/toast"
const TOAST_LIMIT = 1
const TOAST_REMOVE_DELAY = 1000000
type ToasterToast = ToastProps & {
id: string
title?: React.ReactNode
description?: React.ReactNode
action?: ToastActionElement
}
const actionTypes = {
ADD_TOAST: "ADD_TOAST",
UPDATE_TOAST: "UPDATE_TOAST",
DISMISS_TOAST: "DISMISS_TOAST",
REMOVE_TOAST: "REMOVE_TOAST",
} as const
let count = 0
function genId() {
count = (count + 1) % Number.MAX_SAFE_INTEGER
return count.toString()
}
type ActionType = typeof actionTypes
type Action =
| {
type: ActionType["ADD_TOAST"]
toast: ToasterToast
}
| {
type: ActionType["UPDATE_TOAST"]
toast: Partial<ToasterToast>
}
| {
type: ActionType["DISMISS_TOAST"]
toastId?: ToasterToast["id"]
}
| {
type: ActionType["REMOVE_TOAST"]
toastId?: ToasterToast["id"]
}
interface State {
toasts: ToasterToast[]
}
const toastTimeouts = new Map<string, ReturnType<typeof setTimeout>>()
const addToRemoveQueue = (toastId: string) => {
if (toastTimeouts.has(toastId)) {
return
}
const timeout = setTimeout(() => {
toastTimeouts.delete(toastId)
dispatch({
type: "REMOVE_TOAST",
toastId: toastId,
})
}, TOAST_REMOVE_DELAY)
toastTimeouts.set(toastId, timeout)
}
export const reducer = (state: State, action: Action): State => {
switch (action.type) {
case "ADD_TOAST":
return {
...state,
toasts: [action.toast, ...state.toasts].slice(0, TOAST_LIMIT),
}
case "UPDATE_TOAST":
return {
...state,
toasts: state.toasts.map((t) =>
t.id === action.toast.id ? { ...t, ...action.toast } : t
),
}
case "DISMISS_TOAST": {
const { toastId } = action
// ! Side effects ! - This could be extracted into a dismissToast() action,
// but I'll keep it here for simplicity
if (toastId) {
addToRemoveQueue(toastId)
} else {
state.toasts.forEach((toast) => {
addToRemoveQueue(toast.id)
})
}
return {
...state,
toasts: state.toasts.map((t) =>
t.id === toastId || toastId === undefined
? {
...t,
open: false,
}
: t
),
}
}
case "REMOVE_TOAST":
if (action.toastId === undefined) {
return {
...state,
toasts: [],
}
}
return {
...state,
toasts: state.toasts.filter((t) => t.id !== action.toastId),
}
}
}
const listeners: Array<(state: State) => void> = []
let memoryState: State = { toasts: [] }
function dispatch(action: Action) {
memoryState = reducer(memoryState, action)
listeners.forEach((listener) => {
listener(memoryState)
})
}
type Toast = Omit<ToasterToast, "id">
function toast({ ...props }: Toast) {
const id = genId()
const update = (props: ToasterToast) =>
dispatch({
type: "UPDATE_TOAST",
toast: { ...props, id },
})
const dismiss = () => dispatch({ type: "DISMISS_TOAST", toastId: id })
dispatch({
type: "ADD_TOAST",
toast: {
...props,
id,
open: true,
onOpenChange: (open) => {
if (!open) dismiss()
},
},
})
return {
id: id,
dismiss,
update,
}
}
function useToast() {
const [state, setState] = React.useState<State>(memoryState)
React.useEffect(() => {
listeners.push(setState)
return () => {
const index = listeners.indexOf(setState)
if (index > -1) {
listeners.splice(index, 1)
}
}
}, [state])
return {
...state,
toast,
dismiss: (toastId?: string) => dispatch({ type: "DISMISS_TOAST", toastId }),
}
}
export { useToast, toast }

592
node_modules/.package-lock.json generated vendored
View file

@ -26,6 +26,17 @@
"node": ">=6.9.0"
}
},
"node_modules/@emnapi/runtime": {
"version": "1.4.3",
"resolved": "https://registry.npmjs.org/@emnapi/runtime/-/runtime-1.4.3.tgz",
"integrity": "sha512-pBPWdu6MLKROBX05wSNKcNb++m5Er+KQ9QkB+WVM+pW2Kx9hoSrVTnu3BdkI5eBLZoKu/J6mW/B6i6bJB2ytXQ==",
"ideallyInert": true,
"license": "MIT",
"optional": true,
"dependencies": {
"tslib": "^2.4.0"
}
},
"node_modules/@floating-ui/core": {
"version": "1.7.3",
"resolved": "https://registry.npmjs.org/@floating-ui/core/-/core-1.7.3.tgz",
@ -64,6 +75,166 @@
"integrity": "sha512-aGTxbpbg8/b5JfU1HXSrbH3wXZuLPJcNEcZQFMxLs3oSzgtVu6nFPkbbGGUvBcUjKV2YyB9Wxxabo+HEH9tcRQ==",
"license": "MIT"
},
"node_modules/@hookform/resolvers": {
"version": "5.2.2",
"resolved": "https://registry.npmjs.org/@hookform/resolvers/-/resolvers-5.2.2.tgz",
"integrity": "sha512-A/IxlMLShx3KjV/HeTcTfaMxdwy690+L/ZADoeaTltLx+CVuzkeVIPuybK3jrRfw7YZnmdKsVVHAlEPIAEUNlA==",
"license": "MIT",
"dependencies": {
"@standard-schema/utils": "^0.3.0"
},
"peerDependencies": {
"react-hook-form": "^7.55.0"
}
},
"node_modules/@img/sharp-darwin-arm64": {
"version": "0.34.1",
"resolved": "https://registry.npmjs.org/@img/sharp-darwin-arm64/-/sharp-darwin-arm64-0.34.1.tgz",
"integrity": "sha512-pn44xgBtgpEbZsu+lWf2KNb6OAf70X68k+yk69Ic2Xz11zHR/w24/U49XT7AeRwJ0Px+mhALhU5LPci1Aymk7A==",
"cpu": [
"arm64"
],
"ideallyInert": true,
"license": "Apache-2.0",
"optional": true,
"os": [
"darwin"
],
"engines": {
"node": "^18.17.0 || ^20.3.0 || >=21.0.0"
},
"funding": {
"url": "https://opencollective.com/libvips"
},
"optionalDependencies": {
"@img/sharp-libvips-darwin-arm64": "1.1.0"
}
},
"node_modules/@img/sharp-darwin-x64": {
"version": "0.34.1",
"resolved": "https://registry.npmjs.org/@img/sharp-darwin-x64/-/sharp-darwin-x64-0.34.1.tgz",
"integrity": "sha512-VfuYgG2r8BpYiOUN+BfYeFo69nP/MIwAtSJ7/Zpxc5QF3KS22z8Pvg3FkrSFJBPNQ7mmcUcYQFBmEQp7eu1F8Q==",
"cpu": [
"x64"
],
"ideallyInert": true,
"license": "Apache-2.0",
"optional": true,
"os": [
"darwin"
],
"engines": {
"node": "^18.17.0 || ^20.3.0 || >=21.0.0"
},
"funding": {
"url": "https://opencollective.com/libvips"
},
"optionalDependencies": {
"@img/sharp-libvips-darwin-x64": "1.1.0"
}
},
"node_modules/@img/sharp-libvips-darwin-arm64": {
"version": "1.1.0",
"resolved": "https://registry.npmjs.org/@img/sharp-libvips-darwin-arm64/-/sharp-libvips-darwin-arm64-1.1.0.tgz",
"integrity": "sha512-HZ/JUmPwrJSoM4DIQPv/BfNh9yrOA8tlBbqbLz4JZ5uew2+o22Ik+tHQJcih7QJuSa0zo5coHTfD5J8inqj9DA==",
"cpu": [
"arm64"
],
"ideallyInert": true,
"license": "LGPL-3.0-or-later",
"optional": true,
"os": [
"darwin"
],
"funding": {
"url": "https://opencollective.com/libvips"
}
},
"node_modules/@img/sharp-libvips-darwin-x64": {
"version": "1.1.0",
"resolved": "https://registry.npmjs.org/@img/sharp-libvips-darwin-x64/-/sharp-libvips-darwin-x64-1.1.0.tgz",
"integrity": "sha512-Xzc2ToEmHN+hfvsl9wja0RlnXEgpKNmftriQp6XzY/RaSfwD9th+MSh0WQKzUreLKKINb3afirxW7A0fz2YWuQ==",
"cpu": [
"x64"
],
"ideallyInert": true,
"license": "LGPL-3.0-or-later",
"optional": true,
"os": [
"darwin"
],
"funding": {
"url": "https://opencollective.com/libvips"
}
},
"node_modules/@img/sharp-libvips-linux-arm": {
"version": "1.1.0",
"resolved": "https://registry.npmjs.org/@img/sharp-libvips-linux-arm/-/sharp-libvips-linux-arm-1.1.0.tgz",
"integrity": "sha512-s8BAd0lwUIvYCJyRdFqvsj+BJIpDBSxs6ivrOPm/R7piTs5UIwY5OjXrP2bqXC9/moGsyRa37eYWYCOGVXxVrA==",
"cpu": [
"arm"
],
"ideallyInert": true,
"license": "LGPL-3.0-or-later",
"optional": true,
"os": [
"linux"
],
"funding": {
"url": "https://opencollective.com/libvips"
}
},
"node_modules/@img/sharp-libvips-linux-arm64": {
"version": "1.1.0",
"resolved": "https://registry.npmjs.org/@img/sharp-libvips-linux-arm64/-/sharp-libvips-linux-arm64-1.1.0.tgz",
"integrity": "sha512-IVfGJa7gjChDET1dK9SekxFFdflarnUB8PwW8aGwEoF3oAsSDuNUTYS+SKDOyOJxQyDC1aPFMuRYLoDInyV9Ew==",
"cpu": [
"arm64"
],
"ideallyInert": true,
"license": "LGPL-3.0-or-later",
"optional": true,
"os": [
"linux"
],
"funding": {
"url": "https://opencollective.com/libvips"
}
},
"node_modules/@img/sharp-libvips-linux-ppc64": {
"version": "1.1.0",
"resolved": "https://registry.npmjs.org/@img/sharp-libvips-linux-ppc64/-/sharp-libvips-linux-ppc64-1.1.0.tgz",
"integrity": "sha512-tiXxFZFbhnkWE2LA8oQj7KYR+bWBkiV2nilRldT7bqoEZ4HiDOcePr9wVDAZPi/Id5fT1oY9iGnDq20cwUz8lQ==",
"cpu": [
"ppc64"
],
"ideallyInert": true,
"license": "LGPL-3.0-or-later",
"optional": true,
"os": [
"linux"
],
"funding": {
"url": "https://opencollective.com/libvips"
}
},
"node_modules/@img/sharp-libvips-linux-s390x": {
"version": "1.1.0",
"resolved": "https://registry.npmjs.org/@img/sharp-libvips-linux-s390x/-/sharp-libvips-linux-s390x-1.1.0.tgz",
"integrity": "sha512-xukSwvhguw7COyzvmjydRb3x/09+21HykyapcZchiCUkTThEQEOMtBj9UhkaBRLuBrgLFzQ2wbxdeCCJW/jgJA==",
"cpu": [
"s390x"
],
"ideallyInert": true,
"license": "LGPL-3.0-or-later",
"optional": true,
"os": [
"linux"
],
"funding": {
"url": "https://opencollective.com/libvips"
}
},
"node_modules/@img/sharp-libvips-linux-x64": {
"version": "1.1.0",
"resolved": "https://registry.npmjs.org/@img/sharp-libvips-linux-x64/-/sharp-libvips-linux-x64-1.1.0.tgz",
@ -80,6 +251,23 @@
"url": "https://opencollective.com/libvips"
}
},
"node_modules/@img/sharp-libvips-linuxmusl-arm64": {
"version": "1.1.0",
"resolved": "https://registry.npmjs.org/@img/sharp-libvips-linuxmusl-arm64/-/sharp-libvips-linuxmusl-arm64-1.1.0.tgz",
"integrity": "sha512-jYZdG+whg0MDK+q2COKbYidaqW/WTz0cc1E+tMAusiDygrM4ypmSCjOJPmFTvHHJ8j/6cAGyeDWZOsK06tP33w==",
"cpu": [
"arm64"
],
"ideallyInert": true,
"license": "LGPL-3.0-or-later",
"optional": true,
"os": [
"linux"
],
"funding": {
"url": "https://opencollective.com/libvips"
}
},
"node_modules/@img/sharp-libvips-linuxmusl-x64": {
"version": "1.1.0",
"resolved": "https://registry.npmjs.org/@img/sharp-libvips-linuxmusl-x64/-/sharp-libvips-linuxmusl-x64-1.1.0.tgz",
@ -96,6 +284,75 @@
"url": "https://opencollective.com/libvips"
}
},
"node_modules/@img/sharp-linux-arm": {
"version": "0.34.1",
"resolved": "https://registry.npmjs.org/@img/sharp-linux-arm/-/sharp-linux-arm-0.34.1.tgz",
"integrity": "sha512-anKiszvACti2sGy9CirTlNyk7BjjZPiML1jt2ZkTdcvpLU1YH6CXwRAZCA2UmRXnhiIftXQ7+Oh62Ji25W72jA==",
"cpu": [
"arm"
],
"ideallyInert": true,
"license": "Apache-2.0",
"optional": true,
"os": [
"linux"
],
"engines": {
"node": "^18.17.0 || ^20.3.0 || >=21.0.0"
},
"funding": {
"url": "https://opencollective.com/libvips"
},
"optionalDependencies": {
"@img/sharp-libvips-linux-arm": "1.1.0"
}
},
"node_modules/@img/sharp-linux-arm64": {
"version": "0.34.1",
"resolved": "https://registry.npmjs.org/@img/sharp-linux-arm64/-/sharp-linux-arm64-0.34.1.tgz",
"integrity": "sha512-kX2c+vbvaXC6vly1RDf/IWNXxrlxLNpBVWkdpRq5Ka7OOKj6nr66etKy2IENf6FtOgklkg9ZdGpEu9kwdlcwOQ==",
"cpu": [
"arm64"
],
"ideallyInert": true,
"license": "Apache-2.0",
"optional": true,
"os": [
"linux"
],
"engines": {
"node": "^18.17.0 || ^20.3.0 || >=21.0.0"
},
"funding": {
"url": "https://opencollective.com/libvips"
},
"optionalDependencies": {
"@img/sharp-libvips-linux-arm64": "1.1.0"
}
},
"node_modules/@img/sharp-linux-s390x": {
"version": "0.34.1",
"resolved": "https://registry.npmjs.org/@img/sharp-linux-s390x/-/sharp-linux-s390x-0.34.1.tgz",
"integrity": "sha512-7s0KX2tI9mZI2buRipKIw2X1ufdTeaRgwmRabt5bi9chYfhur+/C1OXg3TKg/eag1W+6CCWLVmSauV1owmRPxA==",
"cpu": [
"s390x"
],
"ideallyInert": true,
"license": "Apache-2.0",
"optional": true,
"os": [
"linux"
],
"engines": {
"node": "^18.17.0 || ^20.3.0 || >=21.0.0"
},
"funding": {
"url": "https://opencollective.com/libvips"
},
"optionalDependencies": {
"@img/sharp-libvips-linux-s390x": "1.1.0"
}
},
"node_modules/@img/sharp-linux-x64": {
"version": "0.34.1",
"resolved": "https://registry.npmjs.org/@img/sharp-linux-x64/-/sharp-linux-x64-0.34.1.tgz",
@ -118,6 +375,29 @@
"@img/sharp-libvips-linux-x64": "1.1.0"
}
},
"node_modules/@img/sharp-linuxmusl-arm64": {
"version": "0.34.1",
"resolved": "https://registry.npmjs.org/@img/sharp-linuxmusl-arm64/-/sharp-linuxmusl-arm64-0.34.1.tgz",
"integrity": "sha512-DfvyxzHxw4WGdPiTF0SOHnm11Xv4aQexvqhRDAoD00MzHekAj9a/jADXeXYCDFH/DzYruwHbXU7uz+H+nWmSOQ==",
"cpu": [
"arm64"
],
"ideallyInert": true,
"license": "Apache-2.0",
"optional": true,
"os": [
"linux"
],
"engines": {
"node": "^18.17.0 || ^20.3.0 || >=21.0.0"
},
"funding": {
"url": "https://opencollective.com/libvips"
},
"optionalDependencies": {
"@img/sharp-libvips-linuxmusl-arm64": "1.1.0"
}
},
"node_modules/@img/sharp-linuxmusl-x64": {
"version": "0.34.1",
"resolved": "https://registry.npmjs.org/@img/sharp-linuxmusl-x64/-/sharp-linuxmusl-x64-0.34.1.tgz",
@ -140,6 +420,66 @@
"@img/sharp-libvips-linuxmusl-x64": "1.1.0"
}
},
"node_modules/@img/sharp-wasm32": {
"version": "0.34.1",
"resolved": "https://registry.npmjs.org/@img/sharp-wasm32/-/sharp-wasm32-0.34.1.tgz",
"integrity": "sha512-YDybQnYrLQfEpzGOQe7OKcyLUCML4YOXl428gOOzBgN6Gw0rv8dpsJ7PqTHxBnXnwXr8S1mYFSLSa727tpz0xg==",
"cpu": [
"wasm32"
],
"ideallyInert": true,
"license": "Apache-2.0 AND LGPL-3.0-or-later AND MIT",
"optional": true,
"dependencies": {
"@emnapi/runtime": "^1.4.0"
},
"engines": {
"node": "^18.17.0 || ^20.3.0 || >=21.0.0"
},
"funding": {
"url": "https://opencollective.com/libvips"
}
},
"node_modules/@img/sharp-win32-ia32": {
"version": "0.34.1",
"resolved": "https://registry.npmjs.org/@img/sharp-win32-ia32/-/sharp-win32-ia32-0.34.1.tgz",
"integrity": "sha512-WKf/NAZITnonBf3U1LfdjoMgNO5JYRSlhovhRhMxXVdvWYveM4kM3L8m35onYIdh75cOMCo1BexgVQcCDzyoWw==",
"cpu": [
"ia32"
],
"ideallyInert": true,
"license": "Apache-2.0 AND LGPL-3.0-or-later",
"optional": true,
"os": [
"win32"
],
"engines": {
"node": "^18.17.0 || ^20.3.0 || >=21.0.0"
},
"funding": {
"url": "https://opencollective.com/libvips"
}
},
"node_modules/@img/sharp-win32-x64": {
"version": "0.34.1",
"resolved": "https://registry.npmjs.org/@img/sharp-win32-x64/-/sharp-win32-x64-0.34.1.tgz",
"integrity": "sha512-hw1iIAHpNE8q3uMIRCgGOeDoz9KtFNarFLQclLxr/LK1VBkj8nby18RjFvr6aP7USRYAjTZW6yisnBWMX571Tw==",
"cpu": [
"x64"
],
"ideallyInert": true,
"license": "Apache-2.0 AND LGPL-3.0-or-later",
"optional": true,
"os": [
"win32"
],
"engines": {
"node": "^18.17.0 || ^20.3.0 || >=21.0.0"
},
"funding": {
"url": "https://opencollective.com/libvips"
}
},
"node_modules/@isaacs/cliui": {
"version": "8.0.2",
"resolved": "https://registry.npmjs.org/@isaacs/cliui/-/cliui-8.0.2.tgz",
@ -217,6 +557,74 @@
"integrity": "sha512-xURk++7P7qR9JG1jJtLzPzf0qEvqCN0A/T3DXf8IPMKo9/6FfjxtEffRJIIew/bIL4T3C2jLLqBor8B/zVlx6g==",
"license": "MIT"
},
"node_modules/@next/swc-darwin-arm64": {
"version": "15.3.2",
"resolved": "https://registry.npmjs.org/@next/swc-darwin-arm64/-/swc-darwin-arm64-15.3.2.tgz",
"integrity": "sha512-2DR6kY/OGcokbnCsjHpNeQblqCZ85/1j6njYSkzRdpLn5At7OkSdmk7WyAmB9G0k25+VgqVZ/u356OSoQZ3z0g==",
"cpu": [
"arm64"
],
"ideallyInert": true,
"license": "MIT",
"optional": true,
"os": [
"darwin"
],
"engines": {
"node": ">= 10"
}
},
"node_modules/@next/swc-darwin-x64": {
"version": "15.3.2",
"resolved": "https://registry.npmjs.org/@next/swc-darwin-x64/-/swc-darwin-x64-15.3.2.tgz",
"integrity": "sha512-ro/fdqaZWL6k1S/5CLv1I0DaZfDVJkWNaUU3un8Lg6m0YENWlDulmIWzV96Iou2wEYyEsZq51mwV8+XQXqMp3w==",
"cpu": [
"x64"
],
"ideallyInert": true,
"license": "MIT",
"optional": true,
"os": [
"darwin"
],
"engines": {
"node": ">= 10"
}
},
"node_modules/@next/swc-linux-arm64-gnu": {
"version": "15.3.2",
"resolved": "https://registry.npmjs.org/@next/swc-linux-arm64-gnu/-/swc-linux-arm64-gnu-15.3.2.tgz",
"integrity": "sha512-covwwtZYhlbRWK2HlYX9835qXum4xYZ3E2Mra1mdQ+0ICGoMiw1+nVAn4d9Bo7R3JqSmK1grMq/va+0cdh7bJA==",
"cpu": [
"arm64"
],
"ideallyInert": true,
"license": "MIT",
"optional": true,
"os": [
"linux"
],
"engines": {
"node": ">= 10"
}
},
"node_modules/@next/swc-linux-arm64-musl": {
"version": "15.3.2",
"resolved": "https://registry.npmjs.org/@next/swc-linux-arm64-musl/-/swc-linux-arm64-musl-15.3.2.tgz",
"integrity": "sha512-KQkMEillvlW5Qk5mtGA/3Yz0/tzpNlSw6/3/ttsV1lNtMuOHcGii3zVeXZyi4EJmmLDKYcTcByV2wVsOhDt/zg==",
"cpu": [
"arm64"
],
"ideallyInert": true,
"license": "MIT",
"optional": true,
"os": [
"linux"
],
"engines": {
"node": ">= 10"
}
},
"node_modules/@next/swc-linux-x64-gnu": {
"version": "15.3.2",
"resolved": "https://registry.npmjs.org/@next/swc-linux-x64-gnu/-/swc-linux-x64-gnu-15.3.2.tgz",
@ -249,6 +657,40 @@
"node": ">= 10"
}
},
"node_modules/@next/swc-win32-arm64-msvc": {
"version": "15.3.2",
"resolved": "https://registry.npmjs.org/@next/swc-win32-arm64-msvc/-/swc-win32-arm64-msvc-15.3.2.tgz",
"integrity": "sha512-LLTKmaI5cfD8dVzh5Vt7+OMo+AIOClEdIU/TSKbXXT2iScUTSxOGoBhfuv+FU8R9MLmrkIL1e2fBMkEEjYAtPQ==",
"cpu": [
"arm64"
],
"ideallyInert": true,
"license": "MIT",
"optional": true,
"os": [
"win32"
],
"engines": {
"node": ">= 10"
}
},
"node_modules/@next/swc-win32-x64-msvc": {
"version": "15.3.2",
"resolved": "https://registry.npmjs.org/@next/swc-win32-x64-msvc/-/swc-win32-x64-msvc-15.3.2.tgz",
"integrity": "sha512-aW5B8wOPioJ4mBdMDXkt5f3j8pUr9W8AnlX0Df35uRWNT1Y6RIybxjnSUe+PhM+M1bwgyY8PHLmXZC6zT1o5tA==",
"cpu": [
"x64"
],
"ideallyInert": true,
"license": "MIT",
"optional": true,
"os": [
"win32"
],
"engines": {
"node": ">= 10"
}
},
"node_modules/@nodelib/fs.scandir": {
"version": "2.1.5",
"resolved": "https://registry.npmjs.org/@nodelib/fs.scandir/-/fs.scandir-2.1.5.tgz",
@ -972,6 +1414,119 @@
}
}
},
"node_modules/@radix-ui/react-toast": {
"version": "1.2.15",
"resolved": "https://registry.npmjs.org/@radix-ui/react-toast/-/react-toast-1.2.15.tgz",
"integrity": "sha512-3OSz3TacUWy4WtOXV38DggwxoqJK4+eDkNMl5Z/MJZaoUPaP4/9lf81xXMe1I2ReTAptverZUpbPY4wWwWyL5g==",
"license": "MIT",
"dependencies": {
"@radix-ui/primitive": "1.1.3",
"@radix-ui/react-collection": "1.1.7",
"@radix-ui/react-compose-refs": "1.1.2",
"@radix-ui/react-context": "1.1.2",
"@radix-ui/react-dismissable-layer": "1.1.11",
"@radix-ui/react-portal": "1.1.9",
"@radix-ui/react-presence": "1.1.5",
"@radix-ui/react-primitive": "2.1.3",
"@radix-ui/react-use-callback-ref": "1.1.1",
"@radix-ui/react-use-controllable-state": "1.2.2",
"@radix-ui/react-use-layout-effect": "1.1.1",
"@radix-ui/react-visually-hidden": "1.2.3"
},
"peerDependencies": {
"@types/react": "*",
"@types/react-dom": "*",
"react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc",
"react-dom": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc"
},
"peerDependenciesMeta": {
"@types/react": {
"optional": true
},
"@types/react-dom": {
"optional": true
}
}
},
"node_modules/@radix-ui/react-toast/node_modules/@radix-ui/primitive": {
"version": "1.1.3",
"resolved": "https://registry.npmjs.org/@radix-ui/primitive/-/primitive-1.1.3.tgz",
"integrity": "sha512-JTF99U/6XIjCBo0wqkU5sK10glYe27MRRsfwoiq5zzOEZLHU3A3KCMa5X/azekYRCJ0HlwI0crAXS/5dEHTzDg==",
"license": "MIT"
},
"node_modules/@radix-ui/react-toast/node_modules/@radix-ui/react-collection": {
"version": "1.1.7",
"resolved": "https://registry.npmjs.org/@radix-ui/react-collection/-/react-collection-1.1.7.tgz",
"integrity": "sha512-Fh9rGN0MoI4ZFUNyfFVNU4y9LUz93u9/0K+yLgA2bwRojxM8JU1DyvvMBabnZPBgMWREAJvU2jjVzq+LrFUglw==",
"license": "MIT",
"dependencies": {
"@radix-ui/react-compose-refs": "1.1.2",
"@radix-ui/react-context": "1.1.2",
"@radix-ui/react-primitive": "2.1.3",
"@radix-ui/react-slot": "1.2.3"
},
"peerDependencies": {
"@types/react": "*",
"@types/react-dom": "*",
"react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc",
"react-dom": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc"
},
"peerDependenciesMeta": {
"@types/react": {
"optional": true
},
"@types/react-dom": {
"optional": true
}
}
},
"node_modules/@radix-ui/react-toast/node_modules/@radix-ui/react-presence": {
"version": "1.1.5",
"resolved": "https://registry.npmjs.org/@radix-ui/react-presence/-/react-presence-1.1.5.tgz",
"integrity": "sha512-/jfEwNDdQVBCNvjkGit4h6pMOzq8bHkopq458dPt2lMjx+eBQUohZNG9A7DtO/O5ukSbxuaNGXMjHicgwy6rQQ==",
"license": "MIT",
"dependencies": {
"@radix-ui/react-compose-refs": "1.1.2",
"@radix-ui/react-use-layout-effect": "1.1.1"
},
"peerDependencies": {
"@types/react": "*",
"@types/react-dom": "*",
"react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc",
"react-dom": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc"
},
"peerDependenciesMeta": {
"@types/react": {
"optional": true
},
"@types/react-dom": {
"optional": true
}
}
},
"node_modules/@radix-ui/react-toast/node_modules/@radix-ui/react-primitive": {
"version": "2.1.3",
"resolved": "https://registry.npmjs.org/@radix-ui/react-primitive/-/react-primitive-2.1.3.tgz",
"integrity": "sha512-m9gTwRkhy2lvCPe6QJp4d3G1TYEUHn/FzJUtq9MjH46an1wJU+GdoGC5VLof8RX8Ft/DlpshApkhswDLZzHIcQ==",
"license": "MIT",
"dependencies": {
"@radix-ui/react-slot": "1.2.3"
},
"peerDependencies": {
"@types/react": "*",
"@types/react-dom": "*",
"react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc",
"react-dom": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc"
},
"peerDependenciesMeta": {
"@types/react": {
"optional": true
},
"@types/react-dom": {
"optional": true
}
}
},
"node_modules/@radix-ui/react-use-callback-ref": {
"version": "1.1.1",
"resolved": "https://registry.npmjs.org/@radix-ui/react-use-callback-ref/-/react-use-callback-ref-1.1.1.tgz",
@ -1160,6 +1715,12 @@
"integrity": "sha512-HPwpGIzkl28mWyZqG52jiqDJ12waP11Pa1lGoiyUkIEuMLBP0oeK/C89esbXrxsky5we7dfd8U58nm0SgAWpVw==",
"license": "MIT"
},
"node_modules/@standard-schema/utils": {
"version": "0.3.0",
"resolved": "https://registry.npmjs.org/@standard-schema/utils/-/utils-0.3.0.tgz",
"integrity": "sha512-e7Mew686owMaPJVNNLs55PUvgz371nKgwsc4vxE49zsODpJEnxgxRo2y/OKrqueavXgZNMDVj3DdHFlaSAeU8g==",
"license": "MIT"
},
"node_modules/@swc/counter": {
"version": "0.1.3",
"resolved": "https://registry.npmjs.org/@swc/counter/-/counter-0.1.3.tgz",
@ -1301,6 +1862,7 @@
"resolved": "https://registry.npmjs.org/@types/react/-/react-19.1.2.tgz",
"integrity": "sha512-oxLPMytKchWGbnQM9O7D67uPa9paTNxO7jVoNMXgkkErULBPhPARCfkKL9ytcIJJRGjbsVwW4ugJzyFFvm/Tiw==",
"license": "MIT",
"peer": true,
"dependencies": {
"csstype": "^3.0.2"
}
@ -1494,6 +2056,7 @@
}
],
"license": "MIT",
"peer": true,
"dependencies": {
"caniuse-lite": "^1.0.30001716",
"electron-to-chromium": "^1.5.149",
@ -2141,6 +2704,22 @@
"url": "https://github.com/sponsors/rawify"
}
},
"node_modules/fsevents": {
"version": "2.3.3",
"resolved": "https://registry.npmjs.org/fsevents/-/fsevents-2.3.3.tgz",
"integrity": "sha512-5xoDfX+fL7faATnagmWPpbFtwh/R77WmMMqqHGS65C3vvB0YHrgF+B1YmZ3441tMj5n63k0212XNoJwzlhffQw==",
"dev": true,
"hasInstallScript": true,
"ideallyInert": true,
"license": "MIT",
"optional": true,
"os": [
"darwin"
],
"engines": {
"node": "^8.16.0 || ^10.6.0 || >=11.0.0"
}
},
"node_modules/function-bind": {
"version": "1.1.2",
"resolved": "https://registry.npmjs.org/function-bind/-/function-bind-1.1.2.tgz",
@ -3459,6 +4038,7 @@
}
],
"license": "MIT",
"peer": true,
"dependencies": {
"nanoid": "^3.3.8",
"picocolors": "^1.1.1",
@ -3606,6 +4186,7 @@
"resolved": "https://registry.npmjs.org/react/-/react-19.1.0.tgz",
"integrity": "sha512-FS+XFBNvn3GTAWq26joslQgWNoFu08F4kl0J4CgdNKADkdSGXQyTCnKteIAJy96Br6YbpEU1LSzV5dYtjMkMDg==",
"license": "MIT",
"peer": true,
"engines": {
"node": ">=0.10.0"
}
@ -3615,6 +4196,7 @@
"resolved": "https://registry.npmjs.org/react-dom/-/react-dom-19.1.0.tgz",
"integrity": "sha512-Xs1hdnE+DyKgeHJeJznQmYMIBG3TKIHJJT95Q58nHLSrElKlGQqDTR2HQ9fx5CN/Gk6Vh/kupBTDLU11/nDk/g==",
"license": "MIT",
"peer": true,
"dependencies": {
"scheduler": "^0.26.0"
},
@ -3627,6 +4209,7 @@
"resolved": "https://registry.npmjs.org/react-hook-form/-/react-hook-form-7.63.0.tgz",
"integrity": "sha512-ZwueDMvUeucovM2VjkCf7zIHcs1aAlDimZu2Hvel5C5907gUzMpm4xCrQXtRzCvsBqFjonB4m3x4LzCFI1ZKWA==",
"license": "MIT",
"peer": true,
"engines": {
"node": ">=18.0.0"
},
@ -4792,6 +5375,15 @@
"node": ">= 14"
}
},
"node_modules/zod": {
"version": "4.1.11",
"resolved": "https://registry.npmjs.org/zod/-/zod-4.1.11.tgz",
"integrity": "sha512-WPsqwxITS2tzx1bzhIKsEs19ABD5vmCVa4xBo2tq/SrV4RNZtfws1EnCWQXM6yh8bD08a1idvkB5MZSBiZsjwg==",
"license": "MIT",
"funding": {
"url": "https://github.com/sponsors/colinhacks"
}
},
"node_modules/zwitch": {
"version": "2.0.4",
"resolved": "https://registry.npmjs.org/zwitch/-/zwitch-2.0.4.tgz",

21
node_modules/@hookform/resolvers/LICENSE generated vendored Normal file
View file

@ -0,0 +1,21 @@
MIT License
Copyright (c) 2019-present Beier(Bill) Luo
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.

927
node_modules/@hookform/resolvers/README.md generated vendored Normal file
View file

@ -0,0 +1,927 @@
<div align="center">
<p align="center">
<a href="https://react-hook-form.com" title="React Hook Form - Simple React forms validation">
<img src="https://raw.githubusercontent.com/bluebill1049/react-hook-form/master/docs/logo.png" alt="React Hook Form Logo - React hook custom hook for form validation" />
</a>
</p>
</div>
<p align="center">Performant, flexible and extensible forms with easy to use validation.</p>
<div align="center">
[![npm downloads](https://img.shields.io/npm/dm/@hookform/resolvers.svg?style=for-the-badge)](https://www.npmjs.com/package/@hookform/resolvers)
[![npm](https://img.shields.io/npm/dt/@hookform/resolvers.svg?style=for-the-badge)](https://www.npmjs.com/package/@hookform/resolvers)
[![npm](https://img.shields.io/bundlephobia/minzip/@hookform/resolvers?style=for-the-badge)](https://bundlephobia.com/result?p=@hookform/resolvers)
</div>
## React Hook Form Resolvers
This function allows you to use any external validation library such as Yup, Zod, Joi, Vest, Ajv and many others. The goal is to make sure you can seamlessly integrate whichever validation library you prefer. If you're not using a library, you can always write your own logic to validate your forms.
## Install
Install your preferred validation library alongside `@hookform/resolvers`.
npm install @hookform/resolvers # npm
yarn add @hookform/resolvers # yarn
pnpm install @hookform/resolvers # pnpm
bun install @hookform/resolvers # bun
<details>
<summary>Resolver Comparison</summary>
| resolver | Infer values <br /> from schema | [criteriaMode](https://react-hook-form.com/docs/useform#criteriaMode) |
|---|---|---|
| AJV | ❌ | `firstError \| all` |
| Arktype | ✅ | `firstError` |
| class-validator | ✅ | `firstError \| all` |
| computed-types | ✅ | `firstError` |
| Effect | ✅ | `firstError \| all` |
| fluentvalidation-ts | ❌ | `firstError` |
| io-ts | ✅ | `firstError` |
| joi | ❌ | `firstError \| all` |
| Nope | ❌ | `firstError` |
| Standard Schema | ✅ | `firstError \| all` |
| Superstruct | ✅ | `firstError` |
| typanion | ✅ | `firstError` |
| typebox | ✅ | `firstError \| all` |
| typeschema | ❌ | `firstError \| all` |
| valibot | ✅ | `firstError \| all` |
| vest | ❌ | `firstError \| all` |
| vine | ✅ | `firstError \| all` |
| yup | ✅ | `firstError \| all` |
| zod | ✅ | `firstError \| all` |
</details>
## TypeScript
Most of the resolvers can infer the output type from the schema. See comparison table for more details.
```tsx
useForm<Input, Context, Output>()
```
Example:
```tsx
import { useForm } from 'react-hook-form';
import { zodResolver } from '@hookform/resolvers/zod';
import { z } from 'zod'; // or 'zod/v4'
const schema = z.object({
id: z.number(),
});
// Automatically infers the output type from the schema
useForm({
resolver: zodResolver(schema),
});
// Force the output type
useForm<z.input<typeof schema>, any, z.output<typeof schema>>({
resolver: zodResolver(schema),
});
```
## Links
- [React-hook-form validation resolver documentation ](https://react-hook-form.com/docs/useform#resolver)
### Supported resolvers
- [React Hook Form Resolvers](#react-hook-form-resolvers)
- [Install](#install)
- [TypeScript](#typescript)
- [Links](#links)
- [Supported resolvers](#supported-resolvers)
- [API](#api)
- [Quickstart](#quickstart)
- [Yup](#yup)
- [Zod](#zod)
- [Superstruct](#superstruct)
- [Joi](#joi)
- [Vest](#vest)
- [Class Validator](#class-validator)
- [io-ts](#io-ts)
- [Nope](#nope)
- [computed-types](#computed-types)
- [typanion](#typanion)
- [Ajv](#ajv)
- [TypeBox](#typebox)
- [With `ValueCheck`](#with-valuecheck)
- [With `TypeCompiler`](#with-typecompiler)
- [ArkType](#arktype)
- [Valibot](#valibot)
- [TypeSchema](#typeschema)
- [effect-ts](#effect-ts)
- [VineJS](#vinejs)
- [fluentvalidation-ts](#fluentvalidation-ts)
- [standard-schema](#standard-schema)
- [Backers](#backers)
- [Contributors](#contributors)
## API
```
type Options = {
mode: 'async' | 'sync',
raw?: boolean
}
resolver(schema: object, schemaOptions?: object, resolverOptions: Options)
```
| | type | Required | Description |
| --------------- | -------- | -------- | --------------------------------------------- |
| schema | `object` | ✓ | validation schema |
| schemaOptions | `object` | | validation library schema options |
| resolverOptions | `object` | | resolver options, `async` is the default mode |
## Quickstart
### [Yup](https://github.com/jquense/yup)
Dead simple Object schema validation.
[![npm](https://img.shields.io/bundlephobia/minzip/yup?style=for-the-badge)](https://bundlephobia.com/result?p=yup)
```typescript jsx
import { useForm } from 'react-hook-form';
import { yupResolver } from '@hookform/resolvers/yup';
import * as yup from 'yup';
const schema = yup
.object()
.shape({
name: yup.string().required(),
age: yup.number().required(),
})
.required();
const App = () => {
const { register, handleSubmit } = useForm({
resolver: yupResolver(schema),
});
return (
<form onSubmit={handleSubmit((d) => console.log(d))}>
<input {...register('name')} />
<input type="number" {...register('age')} />
<input type="submit" />
</form>
);
};
```
### [Zod](https://github.com/colinhacks/zod)
TypeScript-first schema validation with static type inference
[![npm](https://img.shields.io/bundlephobia/minzip/zod?style=for-the-badge)](https://bundlephobia.com/result?p=zod)
> ⚠️ Example below uses the `valueAsNumber`, which requires `react-hook-form` v6.12.0 (released Nov 28, 2020) or later.
```tsx
import { useForm } from 'react-hook-form';
import { zodResolver } from '@hookform/resolvers/zod';
import { z } from 'zod'; // or 'zod/v4'
const schema = z.object({
name: z.string().min(1, { message: 'Required' }),
age: z.number().min(10),
});
const App = () => {
const {
register,
handleSubmit,
formState: { errors },
} = useForm({
resolver: zodResolver(schema),
});
return (
<form onSubmit={handleSubmit((d) => console.log(d))}>
<input {...register('name')} />
{errors.name?.message && <p>{errors.name?.message}</p>}
<input type="number" {...register('age', { valueAsNumber: true })} />
{errors.age?.message && <p>{errors.age?.message}</p>}
<input type="submit" />
</form>
);
};
```
### [Superstruct](https://github.com/ianstormtaylor/superstruct)
A simple and composable way to validate data in JavaScript (or TypeScript).
[![npm](https://img.shields.io/bundlephobia/minzip/superstruct?style=for-the-badge)](https://bundlephobia.com/result?p=superstruct)
```typescript jsx
import { useForm } from 'react-hook-form';
import { superstructResolver } from '@hookform/resolvers/superstruct';
import { object, string, number } from 'superstruct';
const schema = object({
name: string(),
age: number(),
});
const App = () => {
const { register, handleSubmit } = useForm({
resolver: superstructResolver(schema),
});
return (
<form onSubmit={handleSubmit((d) => console.log(d))}>
<input {...register('name')} />
<input type="number" {...register('age', { valueAsNumber: true })} />
<input type="submit" />
</form>
);
};
```
### [Joi](https://github.com/sideway/joi)
The most powerful data validation library for JS.
[![npm](https://img.shields.io/bundlephobia/minzip/joi?style=for-the-badge)](https://bundlephobia.com/result?p=joi)
```typescript jsx
import { useForm } from 'react-hook-form';
import { joiResolver } from '@hookform/resolvers/joi';
import Joi from 'joi';
const schema = Joi.object({
name: Joi.string().required(),
age: Joi.number().required(),
});
const App = () => {
const { register, handleSubmit } = useForm({
resolver: joiResolver(schema),
});
return (
<form onSubmit={handleSubmit((d) => console.log(d))}>
<input {...register('name')} />
<input type="number" {...register('age')} />
<input type="submit" />
</form>
);
};
```
### [Vest](https://github.com/ealush/vest)
Vest 🦺 Declarative Validation Testing.
[![npm](https://img.shields.io/bundlephobia/minzip/vest?style=for-the-badge)](https://bundlephobia.com/result?p=vest)
```typescript jsx
import { useForm } from 'react-hook-form';
import { vestResolver } from '@hookform/resolvers/vest';
import { create, test, enforce } from 'vest';
const validationSuite = create((data = {}) => {
test('username', 'Username is required', () => {
enforce(data.username).isNotEmpty();
});
test('password', 'Password is required', () => {
enforce(data.password).isNotEmpty();
});
});
const App = () => {
const { register, handleSubmit, errors } = useForm({
resolver: vestResolver(validationSuite),
});
return (
<form onSubmit={handleSubmit((data) => console.log(data))}>
<input {...register('username')} />
<input type="password" {...register('password')} />
<input type="submit" />
</form>
);
};
```
### [Class Validator](https://github.com/typestack/class-validator)
Decorator-based property validation for classes.
[![npm](https://img.shields.io/bundlephobia/minzip/class-validator?style=for-the-badge)](https://bundlephobia.com/result?p=class-validator)
> ⚠️ Remember to add these options to your `tsconfig.json`!
```
"strictPropertyInitialization": false,
"experimentalDecorators": true
```
```tsx
import { useForm } from 'react-hook-form';
import { classValidatorResolver } from '@hookform/resolvers/class-validator';
import { Length, Min, IsEmail } from 'class-validator';
class User {
@Length(2, 30)
username: string;
@IsEmail()
email: string;
}
const resolver = classValidatorResolver(User);
const App = () => {
const {
register,
handleSubmit,
formState: { errors },
} = useForm<User>({ resolver });
return (
<form onSubmit={handleSubmit((data) => console.log(data))}>
<input type="text" {...register('username')} />
{errors.username && <span>{errors.username.message}</span>}
<input type="text" {...register('email')} />
{errors.email && <span>{errors.email.message}</span>}
<input type="submit" value="Submit" />
</form>
);
};
```
### [io-ts](https://github.com/gcanti/io-ts)
Validate your data with powerful decoders.
[![npm](https://img.shields.io/bundlephobia/minzip/io-ts?style=for-the-badge)](https://bundlephobia.com/result?p=io-ts)
```typescript jsx
import React from 'react';
import { useForm } from 'react-hook-form';
import { ioTsResolver } from '@hookform/resolvers/io-ts';
import t from 'io-ts';
// you don't have to use io-ts-types, but it's very useful
import tt from 'io-ts-types';
const schema = t.type({
username: t.string,
age: tt.NumberFromString,
});
const App = () => {
const { register, handleSubmit } = useForm({
resolver: ioTsResolver(schema),
});
return (
<form onSubmit={handleSubmit((d) => console.log(d))}>
<input {...register('username')} />
<input type="number" {...register('age')} />
<input type="submit" />
</form>
);
};
export default App;
```
### [Nope](https://github.com/bvego/nope-validator)
A small, simple, and fast JS validator
[![npm](https://img.shields.io/bundlephobia/minzip/nope-validator?style=for-the-badge)](https://bundlephobia.com/result?p=nope-validator)
```typescript jsx
import { useForm } from 'react-hook-form';
import { nopeResolver } from '@hookform/resolvers/nope';
import Nope from 'nope-validator';
const schema = Nope.object().shape({
name: Nope.string().required(),
age: Nope.number().required(),
});
const App = () => {
const { register, handleSubmit } = useForm({
resolver: nopeResolver(schema),
});
return (
<form onSubmit={handleSubmit((d) => console.log(d))}>
<input {...register('name')} />
<input type="number" {...register('age')} />
<input type="submit" />
</form>
);
};
```
### [computed-types](https://github.com/neuledge/computed-types)
TypeScript-first schema validation with static type inference
[![npm](https://img.shields.io/bundlephobia/minzip/computed-types?style=for-the-badge)](https://bundlephobia.com/result?p=computed-types)
```tsx
import { useForm } from 'react-hook-form';
import { computedTypesResolver } from '@hookform/resolvers/computed-types';
import Schema, { number, string } from 'computed-types';
const schema = Schema({
username: string.min(1).error('username field is required'),
age: number,
});
const App = () => {
const {
register,
handleSubmit,
formState: { errors },
} = useForm({
resolver: computedTypesResolver(schema),
});
return (
<form onSubmit={handleSubmit((d) => console.log(d))}>
<input {...register('name')} />
{errors.name?.message && <p>{errors.name?.message}</p>}
<input type="number" {...register('age', { valueAsNumber: true })} />
{errors.age?.message && <p>{errors.age?.message}</p>}
<input type="submit" />
</form>
);
};
```
### [typanion](https://github.com/arcanis/typanion)
Static and runtime type assertion library with no dependencies
[![npm](https://img.shields.io/bundlephobia/minzip/typanion?style=for-the-badge)](https://bundlephobia.com/result?p=typanion)
```tsx
import { useForm } from 'react-hook-form';
import { typanionResolver } from '@hookform/resolvers/typanion';
import * as t from 'typanion';
const isUser = t.isObject({
username: t.applyCascade(t.isString(), [t.hasMinLength(1)]),
age: t.applyCascade(t.isNumber(), [
t.isInteger(),
t.isInInclusiveRange(1, 100),
]),
});
const App = () => {
const {
register,
handleSubmit,
formState: { errors },
} = useForm({
resolver: typanionResolver(isUser),
});
return (
<form onSubmit={handleSubmit((d) => console.log(d))}>
<input {...register('name')} />
{errors.name?.message && <p>{errors.name?.message}</p>}
<input type="number" {...register('age')} />
{errors.age?.message && <p>{errors.age?.message}</p>}
<input type="submit" />
</form>
);
};
```
### [Ajv](https://github.com/ajv-validator/ajv)
The fastest JSON validator for Node.js and browser
[![npm](https://img.shields.io/bundlephobia/minzip/ajv?style=for-the-badge)](https://bundlephobia.com/result?p=ajv)
```tsx
import { useForm } from 'react-hook-form';
import { ajvResolver } from '@hookform/resolvers/ajv';
// must use `minLength: 1` to implement required field
const schema = {
type: 'object',
properties: {
username: {
type: 'string',
minLength: 1,
errorMessage: { minLength: 'username field is required' },
},
password: {
type: 'string',
minLength: 1,
errorMessage: { minLength: 'password field is required' },
},
},
required: ['username', 'password'],
additionalProperties: false,
};
const App = () => {
const {
register,
handleSubmit,
formState: { errors },
} = useForm({
resolver: ajvResolver(schema),
});
return (
<form onSubmit={handleSubmit((data) => console.log(data))}>
<input {...register('username')} />
{errors.username && <span>{errors.username.message}</span>}
<input {...register('password')} />
{errors.password && <span>{errors.password.message}</span>}
<button type="submit">submit</button>
</form>
);
};
```
### [TypeBox](https://github.com/sinclairzx81/typebox)
JSON Schema Type Builder with Static Type Resolution for TypeScript
[![npm](https://img.shields.io/bundlephobia/minzip/@sinclair/typebox?style=for-the-badge)](https://bundlephobia.com/result?p=@sinclair/typebox)
#### With `ValueCheck`
```typescript jsx
import { useForm } from 'react-hook-form';
import { typeboxResolver } from '@hookform/resolvers/typebox';
import { Type } from '@sinclair/typebox';
const schema = Type.Object({
username: Type.String({ minLength: 1 }),
password: Type.String({ minLength: 1 }),
});
const App = () => {
const { register, handleSubmit } = useForm({
resolver: typeboxResolver(schema),
});
return (
<form onSubmit={handleSubmit((d) => console.log(d))}>
<input {...register('username')} />
<input type="password" {...register('password')} />
<input type="submit" />
</form>
);
};
```
#### With `TypeCompiler`
A high-performance JIT of `TypeBox`, [read more](https://github.com/sinclairzx81/typebox#typecompiler)
```typescript jsx
import { useForm } from 'react-hook-form';
import { typeboxResolver } from '@hookform/resolvers/typebox';
import { Type } from '@sinclair/typebox';
import { TypeCompiler } from '@sinclair/typebox/compiler';
const schema = Type.Object({
username: Type.String({ minLength: 1 }),
password: Type.String({ minLength: 1 }),
});
const typecheck = TypeCompiler.Compile(schema);
const App = () => {
const { register, handleSubmit } = useForm({
resolver: typeboxResolver(typecheck),
});
return (
<form onSubmit={handleSubmit((d) => console.log(d))}>
<input {...register('username')} />
<input type="password" {...register('password')} />
<input type="submit" />
</form>
);
};
```
### [ArkType](https://github.com/arktypeio/arktype)
TypeScript's 1:1 validator, optimized from editor to runtime
[![npm](https://img.shields.io/bundlephobia/minzip/arktype?style=for-the-badge)](https://bundlephobia.com/result?p=arktype)
```typescript jsx
import { useForm } from 'react-hook-form';
import { arktypeResolver } from '@hookform/resolvers/arktype';
import { type } from 'arktype';
const schema = type({
username: 'string>1',
password: 'string>1',
});
const App = () => {
const { register, handleSubmit } = useForm({
resolver: arktypeResolver(schema),
});
return (
<form onSubmit={handleSubmit((d) => console.log(d))}>
<input {...register('username')} />
<input type="password" {...register('password')} />
<input type="submit" />
</form>
);
};
```
### [Valibot](https://github.com/fabian-hiller/valibot)
The modular and type safe schema library for validating structural data
[![npm](https://img.shields.io/bundlephobia/minzip/valibot?style=for-the-badge)](https://bundlephobia.com/result?p=valibot)
```typescript jsx
import { useForm } from 'react-hook-form';
import { valibotResolver } from '@hookform/resolvers/valibot';
import * as v from 'valibot';
const schema = v.object({
username: v.pipe(
v.string('username is required'),
v.minLength(3, 'Needs to be at least 3 characters'),
v.endsWith('cool', 'Needs to end with `cool`'),
),
password: v.string('password is required'),
});
const App = () => {
const { register, handleSubmit } = useForm({
resolver: valibotResolver(schema),
});
return (
<form onSubmit={handleSubmit((d) => console.log(d))}>
<input {...register('username')} />
<input type="password" {...register('password')} />
<input type="submit" />
</form>
);
};
```
### [TypeSchema](https://typeschema.com)
Universal adapter for schema validation, compatible with [any validation library](https://typeschema.com/#coverage)
[![npm](https://img.shields.io/bundlephobia/minzip/@typeschema/main?style=for-the-badge)](https://bundlephobia.com/result?p=@typeschema/main)
```typescript jsx
import { useForm } from 'react-hook-form';
import { typeschemaResolver } from '@hookform/resolvers/typeschema';
import { z } from 'zod';
// Use your favorite validation library
const schema = z.object({
username: z.string().min(1, { message: 'Required' }),
password: z.number().min(1, { message: 'Required' }),
});
const App = () => {
const { register, handleSubmit } = useForm({
resolver: typeschemaResolver(schema),
});
return (
<form onSubmit={handleSubmit((d) => console.log(d))}>
<input {...register('username')} />
<input type="password" {...register('password')} />
<input type="submit" />
</form>
);
};
```
### [effect-ts](https://github.com/Effect-TS/effect)
A powerful TypeScript framework that provides a fully-fledged functional effect system with a rich standard library.
[![npm](https://img.shields.io/bundlephobia/minzip/effect?style=for-the-badge)](https://bundlephobia.com/result?p=effect)
```typescript jsx
import React from 'react';
import { useForm } from 'react-hook-form';
import { effectTsResolver } from '@hookform/resolvers/effect-ts';
import { Schema } from 'effect';
const schema = Schema.Struct({
username: Schema.String.pipe(
Schema.nonEmptyString({ message: () => 'username required' }),
),
password: Schema.String.pipe(
Schema.nonEmptyString({ message: () => 'password required' }),
),
});
type FormData = typeof schema.Type;
interface Props {
onSubmit: (data: FormData) => void;
}
function TestComponent({ onSubmit }: Props) {
const {
register,
handleSubmit,
formState: { errors },
// provide generic if TS has issues inferring types
} = useForm<FormData>({
resolver: effectTsResolver(schema),
});
return (
<form onSubmit={handleSubmit(onSubmit)}>
<input {...register('username')} />
{errors.username && <span role="alert">{errors.username.message}</span>}
<input {...register('password')} />
{errors.password && <span role="alert">{errors.password.message}</span>}
<button type="submit">submit</button>
</form>
);
}
```
### [VineJS](https://github.com/vinejs/vine)
VineJS is a form data validation library for Node.js
[![npm](https://img.shields.io/bundlephobia/minzip/@vinejs/vine?style=for-the-badge)](https://bundlephobia.com/result?p=@vinejs/vine)
```typescript jsx
import { useForm } from 'react-hook-form';
import { vineResolver } from '@hookform/resolvers/vine';
import vine from '@vinejs/vine';
const schema = vine.compile(
vine.object({
username: vine.string().minLength(1),
password: vine.string().minLength(1),
}),
);
const App = () => {
const { register, handleSubmit } = useForm({
resolver: vineResolver(schema),
});
return (
<form onSubmit={handleSubmit((d) => console.log(d))}>
<input {...register('username')} />
{errors.username && <span role="alert">{errors.username.message}</span>}
<input {...register('password')} />
{errors.password && <span role="alert">{errors.password.message}</span>}
<button type="submit">submit</button>
</form>
);
};
```
### [fluentvalidation-ts](https://github.com/AlexJPotter/fluentvalidation-ts)
A TypeScript-first library for building strongly-typed validation rules
[![npm](https://img.shields.io/bundlephobia/minzip/@vinejs/vine?style=for-the-badge)](https://bundlephobia.com/result?p=@vinejs/vine)
```typescript jsx
import { useForm } from 'react-hook-form';
import { fluentValidationResolver } from '@hookform/resolvers/fluentvalidation-ts';
import { Validator } from 'fluentvalidation-ts';
class FormDataValidator extends Validator<FormData> {
constructor() {
super();
this.ruleFor('username')
.notEmpty()
.withMessage('username is a required field');
this.ruleFor('password')
.notEmpty()
.withMessage('password is a required field');
}
}
const App = () => {
const { register, handleSubmit } = useForm({
resolver: fluentValidationResolver(new FormDataValidator()),
});
return (
<form onSubmit={handleSubmit((d) => console.log(d))}>
<input {...register('username')} />
{errors.username && <span role="alert">{errors.username.message}</span>}
<input {...register('password')} />
{errors.password && <span role="alert">{errors.password.message}</span>}
<button type="submit">submit</button>
</form>
);
};
```
### [standard-schema](https://github.com/standard-schema/standard-schema)
A standard interface for TypeScript schema validation libraries
[![npm](https://img.shields.io/bundlephobia/minzip/@standard-schema/spec?style=for-the-badge)](https://bundlephobia.com/result?p=@standard-schema/spec)
Example zod
```typescript jsx
import { useForm } from 'react-hook-form';
import { standardSchemaResolver } from '@hookform/resolvers/standard-schema';
import { z } from 'zod';
const schema = z.object({
name: z.string().min(1, { message: 'Required' }),
age: z.number().min(10),
});
const App = () => {
const {
register,
handleSubmit,
formState: { errors },
} = useForm({
resolver: standardSchemaResolver(schema),
});
return (
<form onSubmit={handleSubmit((d) => console.log(d))}>
<input {...register('name')} />
{errors.name?.message && <p>{errors.name?.message}</p>}
<input type="number" {...register('age', { valueAsNumber: true })} />
{errors.age?.message && <p>{errors.age?.message}</p>}
<input type="submit" />
</form>
);
};
```
Example arkType
```typescript jsx
import { useForm } from 'react-hook-form';
import { standardSchemaResolver } from '@hookform/resolvers/standard-schema';
import { type } from 'arktype';
const schema = type({
username: 'string>1',
password: 'string>1',
});
const App = () => {
const { register, handleSubmit } = useForm({
resolver: standardSchemaResolver(schema),
});
return (
<form onSubmit={handleSubmit((d) => console.log(d))}>
<input {...register('username')} />
<input type="password" {...register('password')} />
<input type="submit" />
</form>
);
};
```
## Backers
Thanks go to all our backers! [[Become a backer](https://opencollective.com/react-hook-form#backer)].
<a href="https://opencollective.com/react-hook-form#backers">
<img src="https://opencollective.com/react-hook-form/backers.svg?width=950" />
</a>
## Contributors
Thanks go to these wonderful people! [[Become a contributor](CONTRIBUTING.md)].
<a href="https://github.com/react-hook-form/react-hook-form/graphs/contributors">
<img src="https://opencollective.com/react-hook-form/contributors.svg?width=950" />
</a>

22
node_modules/@hookform/resolvers/ajv/dist/ajv.d.ts generated vendored Normal file
View file

@ -0,0 +1,22 @@
import { Resolver } from './types';
/**
* Creates a resolver for react-hook-form using Ajv schema validation
* @param {Schema} schema - The Ajv schema to validate against
* @param {Object} schemaOptions - Additional schema validation options
* @param {Object} resolverOptions - Additional resolver configuration
* @param {string} [resolverOptions.mode='async'] - Validation mode
* @returns {Resolver<Schema>} A resolver function compatible with react-hook-form
* @example
* const schema = ajv.compile({
* type: 'object',
* properties: {
* name: { type: 'string' },
* age: { type: 'number' }
* }
* });
*
* useForm({
* resolver: ajvResolver(schema)
* });
*/
export declare const ajvResolver: Resolver;

2
node_modules/@hookform/resolvers/ajv/dist/ajv.js generated vendored Normal file
View file

@ -0,0 +1,2 @@
var e=require("@hookform/resolvers"),r=require("ajv"),a=require("ajv-errors"),s=require("ajv-formats"),o=require("react-hook-form");function t(e){return e&&"object"==typeof e&&"default"in e?e:{default:e}}var i=/*#__PURE__*/t(r),n=/*#__PURE__*/t(a),u=/*#__PURE__*/t(s),c=function(e,r){for(var a={},s=function(e){"required"===e.keyword&&(e.instancePath+="/"+e.params.missingProperty);var s=e.instancePath.substring(1).replace(/\//g,".");if(a[s]||(a[s]={message:e.message,type:e.keyword}),r){var t=a[s].types,i=t&&t[e.keyword];a[s]=o.appendErrors(s,r,a,e.keyword,i?[].concat(i,e.message||""):e.message)}},t=function(){var r=e[i];"errorMessage"===r.keyword?r.params.errors.forEach(function(e){e.message=r.message,s(e)}):s(r)},i=0;i<e.length;i+=1)t();return a};exports.ajvResolver=function(r,a,s){return void 0===s&&(s={}),function(o,t,l){try{var v=new i.default(Object.assign({},{allErrors:!0,validateSchema:!0},a));n.default(v),u.default(v);var d=v.compile(Object.assign({$async:s&&"async"===s.mode},r)),f=d(o);return l.shouldUseNativeValidation&&e.validateFieldsNatively({},l),Promise.resolve(f?{values:o,errors:{}}:{values:{},errors:e.toNestErrors(c(d.errors,!l.shouldUseNativeValidation&&"all"===l.criteriaMode),l)})}catch(e){return Promise.reject(e)}}};
//# sourceMappingURL=ajv.js.map

1
node_modules/@hookform/resolvers/ajv/dist/ajv.js.map generated vendored Normal file

File diff suppressed because one or more lines are too long

2
node_modules/@hookform/resolvers/ajv/dist/ajv.mjs generated vendored Normal file
View file

@ -0,0 +1,2 @@
import{validateFieldsNatively as r,toNestErrors as e}from"@hookform/resolvers";import o from"ajv";import a from"ajv-errors";import s from"ajv-formats";import{appendErrors as t}from"react-hook-form";var i=function(r,e){for(var o={},a=function(r){"required"===r.keyword&&(r.instancePath+="/"+r.params.missingProperty);var a=r.instancePath.substring(1).replace(/\//g,".");if(o[a]||(o[a]={message:r.message,type:r.keyword}),e){var s=o[a].types,i=s&&s[r.keyword];o[a]=t(a,e,o,r.keyword,i?[].concat(i,r.message||""):r.message)}},s=function(){var e=r[i];"errorMessage"===e.keyword?e.params.errors.forEach(function(r){r.message=e.message,a(r)}):a(e)},i=0;i<r.length;i+=1)s();return o},n=function(t,n,m){return void 0===m&&(m={}),function(c,v,f){try{var l=new o(Object.assign({},{allErrors:!0,validateSchema:!0},n));a(l),s(l);var u=l.compile(Object.assign({$async:m&&"async"===m.mode},t)),d=u(c);return f.shouldUseNativeValidation&&r({},f),Promise.resolve(d?{values:c,errors:{}}:{values:{},errors:e(i(u.errors,!f.shouldUseNativeValidation&&"all"===f.criteriaMode),f)})}catch(r){return Promise.reject(r)}}};export{n as ajvResolver};
//# sourceMappingURL=ajv.module.js.map

View file

@ -0,0 +1,2 @@
import{validateFieldsNatively as r,toNestErrors as e}from"@hookform/resolvers";import s from"ajv";import o from"ajv-errors";import a from"ajv-formats";import{appendErrors as t}from"react-hook-form";const m=(r,e)=>{const s={},o=r=>{"required"===r.keyword&&(r.instancePath+=`/${r.params.missingProperty}`);const o=r.instancePath.substring(1).replace(/\//g,".");if(s[o]||(s[o]={message:r.message,type:r.keyword}),e){const a=s[o].types,m=a&&a[r.keyword];s[o]=t(o,e,s,r.keyword,m?[].concat(m,r.message||""):r.message)}};for(let e=0;e<r.length;e+=1){const s=r[e];"errorMessage"===s.keyword?s.params.errors.forEach(r=>{r.message=s.message,o(r)}):o(s)}return s},n=(t,n,i={})=>async(c,l,d)=>{const g=new s(Object.assign({},{allErrors:!0,validateSchema:!0},n));o(g),a(g);const p=g.compile(Object.assign({$async:i&&"async"===i.mode},t)),f=p(c);return d.shouldUseNativeValidation&&r({},d),f?{values:c,errors:{}}:{values:{},errors:e(m(p.errors,!d.shouldUseNativeValidation&&"all"===d.criteriaMode),d)}};export{n as ajvResolver};
//# sourceMappingURL=ajv.modern.mjs.map

File diff suppressed because one or more lines are too long

View file

@ -0,0 +1,2 @@
import{validateFieldsNatively as r,toNestErrors as e}from"@hookform/resolvers";import o from"ajv";import a from"ajv-errors";import s from"ajv-formats";import{appendErrors as t}from"react-hook-form";var i=function(r,e){for(var o={},a=function(r){"required"===r.keyword&&(r.instancePath+="/"+r.params.missingProperty);var a=r.instancePath.substring(1).replace(/\//g,".");if(o[a]||(o[a]={message:r.message,type:r.keyword}),e){var s=o[a].types,i=s&&s[r.keyword];o[a]=t(a,e,o,r.keyword,i?[].concat(i,r.message||""):r.message)}},s=function(){var e=r[i];"errorMessage"===e.keyword?e.params.errors.forEach(function(r){r.message=e.message,a(r)}):a(e)},i=0;i<r.length;i+=1)s();return o},n=function(t,n,m){return void 0===m&&(m={}),function(c,v,f){try{var l=new o(Object.assign({},{allErrors:!0,validateSchema:!0},n));a(l),s(l);var u=l.compile(Object.assign({$async:m&&"async"===m.mode},t)),d=u(c);return f.shouldUseNativeValidation&&r({},f),Promise.resolve(d?{values:c,errors:{}}:{values:{},errors:e(i(u.errors,!f.shouldUseNativeValidation&&"all"===f.criteriaMode),f)})}catch(r){return Promise.reject(r)}}};export{n as ajvResolver};
//# sourceMappingURL=ajv.module.js.map

File diff suppressed because one or more lines are too long

2
node_modules/@hookform/resolvers/ajv/dist/ajv.umd.js generated vendored Normal file
View file

@ -0,0 +1,2 @@
!function(e,r){"object"==typeof exports&&"undefined"!=typeof module?r(exports,require("@hookform/resolvers"),require("ajv"),require("ajv-errors"),require("ajv-formats"),require("react-hook-form")):"function"==typeof define&&define.amd?define(["exports","@hookform/resolvers","ajv","ajv-errors","ajv-formats","react-hook-form"],r):r((e||self).hookformResolversAjv={},e.hookformResolvers,e.ajv,e.ajvErrors,e.ajvFormats,e.ReactHookForm)}(this,function(e,r,o,a,s,t){function i(e){return e&&"object"==typeof e&&"default"in e?e:{default:e}}var n=/*#__PURE__*/i(o),f=/*#__PURE__*/i(a),l=/*#__PURE__*/i(s),u=function(e,r){for(var o={},a=function(e){"required"===e.keyword&&(e.instancePath+="/"+e.params.missingProperty);var a=e.instancePath.substring(1).replace(/\//g,".");if(o[a]||(o[a]={message:e.message,type:e.keyword}),r){var s=o[a].types,i=s&&s[e.keyword];o[a]=t.appendErrors(a,r,o,e.keyword,i?[].concat(i,e.message||""):e.message)}},s=function(){var r=e[i];"errorMessage"===r.keyword?r.params.errors.forEach(function(e){e.message=r.message,a(e)}):a(r)},i=0;i<e.length;i+=1)s();return o};e.ajvResolver=function(e,o,a){return void 0===a&&(a={}),function(s,t,i){try{var v=new n.default(Object.assign({},{allErrors:!0,validateSchema:!0},o));f.default(v),l.default(v);var c=v.compile(Object.assign({$async:a&&"async"===a.mode},e)),d=c(s);return i.shouldUseNativeValidation&&r.validateFieldsNatively({},i),Promise.resolve(d?{values:s,errors:{}}:{values:{},errors:r.toNestErrors(u(c.errors,!i.shouldUseNativeValidation&&"all"===i.criteriaMode),i)})}catch(e){return Promise.reject(e)}}}});
//# sourceMappingURL=ajv.umd.js.map

File diff suppressed because one or more lines are too long

2
node_modules/@hookform/resolvers/ajv/dist/index.d.ts generated vendored Normal file
View file

@ -0,0 +1,2 @@
export * from './ajv';
export * from './types';

13
node_modules/@hookform/resolvers/ajv/dist/types.d.ts generated vendored Normal file
View file

@ -0,0 +1,13 @@
import * as Ajv from 'ajv';
import type { DefinedError, ErrorObject } from 'ajv';
import { FieldValues, ResolverOptions, ResolverResult } from 'react-hook-form';
export type Resolver = <T>(schema: Ajv.JSONSchemaType<T>, schemaOptions?: Ajv.Options, factoryOptions?: {
mode?: 'async' | 'sync';
}) => <TFieldValues extends FieldValues, TContext>(values: TFieldValues, context: TContext | undefined, options: ResolverOptions<TFieldValues>) => Promise<ResolverResult<TFieldValues>>;
type ErrorMessage = ErrorObject<'errorMessage', {
errors: (DefinedError & {
emUsed: boolean;
})[];
}>;
export type AjvError = ErrorMessage | DefinedError;
export {};

20
node_modules/@hookform/resolvers/ajv/package.json generated vendored Normal file
View file

@ -0,0 +1,20 @@
{
"name": "@hookform/resolvers/ajv",
"amdName": "hookformResolversAjv",
"version": "1.0.0",
"private": true,
"description": "React Hook Form validation resolver: ajv",
"main": "dist/ajv.js",
"module": "dist/ajv.module.js",
"umd:main": "dist/ajv.umd.js",
"source": "src/index.ts",
"types": "dist/index.d.ts",
"license": "MIT",
"peerDependencies": {
"react-hook-form": "^7.55.0",
"@hookform/resolvers": "^2.0.0",
"ajv": "^8.12.0",
"ajv-errors": "^3.0.0",
"ajv-formats": "^2.1.1"
}
}

View file

@ -0,0 +1,94 @@
import { render, screen } from '@testing-library/react';
import user from '@testing-library/user-event';
import { JSONSchemaType } from 'ajv';
import React from 'react';
import { useForm } from 'react-hook-form';
import { ajvResolver } from '..';
const USERNAME_REQUIRED_MESSAGE = 'username field is required';
const PASSWORD_REQUIRED_MESSAGE = 'password field is required';
type FormData = { username: string; password: string };
const schema: JSONSchemaType<FormData> = {
type: 'object',
properties: {
username: {
type: 'string',
minLength: 1,
errorMessage: { minLength: USERNAME_REQUIRED_MESSAGE },
},
password: {
type: 'string',
minLength: 1,
errorMessage: { minLength: PASSWORD_REQUIRED_MESSAGE },
},
},
required: ['username', 'password'],
additionalProperties: false,
};
interface Props {
onSubmit: (data: FormData) => void;
}
function TestComponent({ onSubmit }: Props) {
const { register, handleSubmit } = useForm<FormData>({
resolver: ajvResolver(schema),
shouldUseNativeValidation: true,
});
return (
<form onSubmit={handleSubmit(onSubmit)}>
<input {...register('username')} placeholder="username" />
<input {...register('password')} placeholder="password" />
<button type="submit">submit</button>
</form>
);
}
test("form's native validation with Ajv", async () => {
const handleSubmit = vi.fn();
render(<TestComponent onSubmit={handleSubmit} />);
// username
let usernameField = screen.getByPlaceholderText(
/username/i,
) as HTMLInputElement;
expect(usernameField.validity.valid).toBe(true);
expect(usernameField.validationMessage).toBe('');
// password
let passwordField = screen.getByPlaceholderText(
/password/i,
) as HTMLInputElement;
expect(passwordField.validity.valid).toBe(true);
expect(passwordField.validationMessage).toBe('');
await user.click(screen.getByText(/submit/i));
// username
usernameField = screen.getByPlaceholderText(/username/i) as HTMLInputElement;
expect(usernameField.validity.valid).toBe(false);
expect(usernameField.validationMessage).toBe(USERNAME_REQUIRED_MESSAGE);
// password
passwordField = screen.getByPlaceholderText(/password/i) as HTMLInputElement;
expect(passwordField.validity.valid).toBe(false);
expect(passwordField.validationMessage).toBe(PASSWORD_REQUIRED_MESSAGE);
await user.type(screen.getByPlaceholderText(/username/i), 'joe');
await user.type(screen.getByPlaceholderText(/password/i), 'password');
// username
usernameField = screen.getByPlaceholderText(/username/i) as HTMLInputElement;
expect(usernameField.validity.valid).toBe(true);
expect(usernameField.validationMessage).toBe('');
// password
passwordField = screen.getByPlaceholderText(/password/i) as HTMLInputElement;
expect(passwordField.validity.valid).toBe(true);
expect(passwordField.validationMessage).toBe('');
});

View file

@ -0,0 +1,65 @@
import { render, screen } from '@testing-library/react';
import user from '@testing-library/user-event';
import { JSONSchemaType } from 'ajv';
import React from 'react';
import { useForm } from 'react-hook-form';
import { ajvResolver } from '..';
type FormData = { username: string; password: string };
const schema: JSONSchemaType<FormData> = {
type: 'object',
properties: {
username: {
type: 'string',
minLength: 1,
errorMessage: { minLength: 'username field is required' },
},
password: {
type: 'string',
minLength: 1,
errorMessage: { minLength: 'password field is required' },
},
},
required: ['username', 'password'],
additionalProperties: false,
};
interface Props {
onSubmit: (data: FormData) => void;
}
function TestComponent({ onSubmit }: Props) {
const {
register,
formState: { errors },
handleSubmit,
} = useForm<FormData>({
resolver: ajvResolver(schema), // Useful to check TypeScript regressions
});
return (
<form onSubmit={handleSubmit(onSubmit)}>
<input {...register('username')} />
{errors.username && <span role="alert">{errors.username.message}</span>}
<input {...register('password')} />
{errors.password && <span role="alert">{errors.password.message}</span>}
<button type="submit">submit</button>
</form>
);
}
test("form's validation with Ajv and TypeScript's integration", async () => {
const handleSubmit = vi.fn();
render(<TestComponent onSubmit={handleSubmit} />);
expect(screen.queryAllByRole('alert')).toHaveLength(0);
await user.click(screen.getByText(/submit/i));
expect(screen.getByText(/username field is required/i)).toBeInTheDocument();
expect(screen.getByText(/password field is required/i)).toBeInTheDocument();
expect(handleSubmit).not.toHaveBeenCalled();
});

View file

@ -0,0 +1,216 @@
import { JSONSchemaType } from 'ajv';
import { Field, InternalFieldName } from 'react-hook-form';
interface DataA {
username: string;
password: string;
}
export const schemaA: JSONSchemaType<DataA> = {
type: 'object',
properties: {
username: {
type: 'string',
minLength: 3,
errorMessage: {
minLength: 'username should be at least three characters long',
},
},
password: {
type: 'string',
pattern: '.*[A-Z].*',
minLength: 8,
errorMessage: {
pattern: 'One uppercase character',
minLength: 'passwords should be at least eight characters long',
},
},
},
required: ['username', 'password'],
additionalProperties: false,
errorMessage: {
required: {
username: 'username field is required',
password: 'password field is required',
},
},
};
export const validDataA: DataA = {
username: 'kt666',
password: 'validPassword',
};
export const invalidDataA = {
username: 'kt',
password: 'invalid',
};
export const undefinedDataA = {
username: undefined,
password: undefined,
};
export const fieldsA: Record<InternalFieldName, Field['_f']> = {
username: {
ref: { name: 'username' },
name: 'username',
},
password: {
ref: { name: 'password' },
name: 'password',
},
email: {
ref: { name: 'email' },
name: 'email',
},
birthday: {
ref: { name: 'birthday' },
name: 'birthday',
},
};
// examples from [ajv-errors](https://github.com/ajv-validator/ajv-errors)
interface DataB {
foo: number;
}
export const schemaB: JSONSchemaType<DataB> = {
type: 'object',
required: ['foo'],
properties: {
foo: { type: 'integer' },
},
additionalProperties: false,
errorMessage: 'should be an object with an integer property foo only',
};
export const validDataB: DataB = { foo: 666 };
export const invalidDataB = { foo: 'kt', bar: 6 };
export const undefinedDataB = { foo: undefined };
interface DataC {
foo: number;
}
export const schemaC: JSONSchemaType<DataC> = {
type: 'object',
required: ['foo'],
properties: {
foo: { type: 'integer' },
},
additionalProperties: false,
errorMessage: {
type: 'should be an object',
required: 'should have property foo',
additionalProperties: 'should not have properties other than foo',
},
};
export const validDataC: DataC = { foo: 666 };
export const invalidDataC = { foo: 'kt', bar: 6 };
export const undefinedDataC = { foo: undefined };
export const invalidTypeDataC = 'something';
interface DataD {
foo: number;
bar: string;
}
export const schemaD: JSONSchemaType<DataD> = {
type: 'object',
required: ['foo', 'bar'],
properties: {
foo: { type: 'integer' },
bar: { type: 'string' },
},
errorMessage: {
type: 'should be an object', // will not replace internal "type" error for the property "foo"
required: {
foo: 'should have an integer property "foo"',
bar: 'should have a string property "bar"',
},
},
};
export const validDataD: DataD = { foo: 666, bar: 'kt' };
export const invalidDataD = { foo: 'kt', bar: 6 };
export const undefinedDataD = { foo: undefined, bar: undefined };
export const invalidTypeDataD = 'something';
interface DataE {
foo: number;
bar: string;
}
export const schemaE: JSONSchemaType<DataE> = {
type: 'object',
required: ['foo', 'bar'],
allOf: [
{
properties: {
foo: { type: 'integer', minimum: 2 },
bar: { type: 'string', minLength: 2 },
},
additionalProperties: false,
},
],
errorMessage: {
properties: {
foo: 'data.foo should be integer >= 2',
bar: 'data.bar should be string with length >= 2',
},
},
};
export const validDataE: DataE = { foo: 666, bar: 'kt' };
export const invalidDataE = { foo: 1, bar: 'k' };
export const undefinedDataE = { foo: undefined, bar: undefined };
interface DataF {
foo: number;
bar: string;
}
export const schemaF: JSONSchemaType<DataF> = {
type: 'object',
required: ['foo', 'bar'],
allOf: [
{
properties: {
foo: { type: 'integer', minimum: 2 },
bar: { type: 'string', minLength: 2 },
},
additionalProperties: false,
},
],
errorMessage: {
type: 'data should be an object',
properties: {
foo: 'data.foo should be integer >= 2',
bar: 'data.bar should be string with length >= 2',
},
_: 'data should have properties "foo" and "bar" only',
},
};
export const validDataF: DataF = { foo: 666, bar: 'kt' };
export const invalidDataF = {};
export const undefinedDataF = { foo: 1, bar: undefined };
export const invalidTypeDataF = 'something';
export const fieldsRest: Record<InternalFieldName, Field['_f']> = {
foo: {
ref: { name: 'foo' },
name: 'foo',
},
bar: {
ref: { name: 'bar' },
name: 'bar',
},
lorem: {
ref: { name: 'lorem' },
name: 'lorem',
},
};

View file

@ -0,0 +1,90 @@
import { JSONSchemaType } from 'ajv';
import { Field, InternalFieldName } from 'react-hook-form';
interface Data {
username: string;
password: string;
deepObject: { data: string; twoLayersDeep: { name: string } };
}
export const schema: JSONSchemaType<Data> = {
type: 'object',
properties: {
username: {
type: 'string',
minLength: 3,
},
password: {
type: 'string',
pattern: '.*[A-Z].*',
errorMessage: {
pattern: 'One uppercase character',
},
},
deepObject: {
type: 'object',
properties: {
data: { type: 'string' },
twoLayersDeep: {
type: 'object',
properties: { name: { type: 'string' } },
additionalProperties: false,
required: ['name'],
},
},
required: ['data', 'twoLayersDeep'],
},
},
required: ['username', 'password', 'deepObject'],
additionalProperties: false,
};
export const validData: Data = {
username: 'jsun969',
password: 'validPassword',
deepObject: {
twoLayersDeep: {
name: 'deeper',
},
data: 'data',
},
};
export const invalidData = {
username: '__',
password: 'invalid-password',
deepObject: {
data: 233,
twoLayersDeep: { name: 123 },
},
};
export const invalidDataWithUndefined = {
username: 'jsun969',
password: undefined,
deepObject: {
twoLayersDeep: {
name: 'deeper',
},
data: undefined,
},
};
export const fields: Record<InternalFieldName, Field['_f']> = {
username: {
ref: { name: 'username' },
name: 'username',
},
password: {
ref: { name: 'password' },
name: 'password',
},
email: {
ref: { name: 'email' },
name: 'email',
},
birthday: {
ref: { name: 'birthday' },
name: 'birthday',
},
};

View file

@ -0,0 +1,462 @@
// Vitest Snapshot v1, https://vitest.dev/guide/snapshot.html
exports[`ajvResolver with errorMessage > should return a default message if there is no specific message for the error when requirement fails 1`] = `
{
"errors": {
"bar": {
"message": "data should have properties "foo" and "bar" only",
"ref": {
"name": "bar",
},
"type": "required",
"types": {
"required": "data should have properties "foo" and "bar" only",
},
},
"foo": {
"message": "data should have properties "foo" and "bar" only",
"ref": {
"name": "foo",
},
"type": "required",
"types": {
"required": "data should have properties "foo" and "bar" only",
},
},
},
"values": {},
}
`;
exports[`ajvResolver with errorMessage > should return a default message if there is no specific message for the error when some properties are undefined 1`] = `
{
"errors": {
"bar": {
"message": "data should have properties "foo" and "bar" only",
"ref": {
"name": "bar",
},
"type": "required",
"types": {
"required": "data should have properties "foo" and "bar" only",
},
},
"foo": {
"message": "data.foo should be integer >= 2",
"ref": {
"name": "foo",
},
"type": "minimum",
"types": {
"minimum": "data.foo should be integer >= 2",
},
},
},
"values": {},
}
`;
exports[`ajvResolver with errorMessage > should return a default message if there is no specific message for the error when walidation fails 1`] = `
{
"errors": {
"bar": {
"message": "data should have properties "foo" and "bar" only",
"ref": {
"name": "bar",
},
"type": "required",
"types": {
"required": "data should have properties "foo" and "bar" only",
},
},
"foo": {
"message": "data should have properties "foo" and "bar" only",
"ref": {
"name": "foo",
},
"type": "required",
"types": {
"required": "data should have properties "foo" and "bar" only",
},
},
},
"values": {},
}
`;
exports[`ajvResolver with errorMessage > should return customized error messages for certain keywords when requirement fails 1`] = `
{
"errors": {
"foo": {
"message": "should have property foo",
"ref": {
"name": "foo",
},
"type": "required",
"types": {
"required": "should have property foo",
},
},
},
"values": {},
}
`;
exports[`ajvResolver with errorMessage > should return customized error messages for certain keywords when some properties are undefined 1`] = `
{
"errors": {
"foo": {
"message": "should have property foo",
"ref": {
"name": "foo",
},
"type": "required",
"types": {
"required": "should have property foo",
},
},
},
"values": {},
}
`;
exports[`ajvResolver with errorMessage > should return customized error messages for certain keywords when walidation fails 1`] = `
{
"errors": {
"": {
"message": "should not have properties other than foo",
"ref": undefined,
"type": "additionalProperties",
"types": {
"additionalProperties": "should not have properties other than foo",
},
},
"foo": {
"message": "must be integer",
"ref": {
"name": "foo",
},
"type": "type",
"types": {
"type": "must be integer",
},
},
},
"values": {},
}
`;
exports[`ajvResolver with errorMessage > should return customized error messages when requirement fails 1`] = `
{
"errors": {
"password": {
"message": "password field is required",
"ref": {
"name": "password",
},
"type": "required",
"types": {
"required": "password field is required",
},
},
"username": {
"message": "username field is required",
"ref": {
"name": "username",
},
"type": "required",
"types": {
"required": "username field is required",
},
},
},
"values": {},
}
`;
exports[`ajvResolver with errorMessage > should return customized error messages when some properties are undefined 1`] = `
{
"errors": {
"password": {
"message": "password field is required",
"ref": {
"name": "password",
},
"type": "required",
"types": {
"required": "password field is required",
},
},
"username": {
"message": "username field is required",
"ref": {
"name": "username",
},
"type": "required",
"types": {
"required": "username field is required",
},
},
},
"values": {},
}
`;
exports[`ajvResolver with errorMessage > should return customized error messages when validation fails 1`] = `
{
"errors": {
"password": {
"message": "One uppercase character",
"ref": {
"name": "password",
},
"type": "pattern",
"types": {
"minLength": "passwords should be at least eight characters long",
"pattern": "One uppercase character",
},
},
"username": {
"message": "username should be at least three characters long",
"ref": {
"name": "username",
},
"type": "minLength",
"types": {
"minLength": "username should be at least three characters long",
},
},
},
"values": {},
}
`;
exports[`ajvResolver with errorMessage > should return customized errors for properties/items when requirement fails 1`] = `
{
"errors": {
"bar": {
"message": "must have required property 'bar'",
"ref": {
"name": "bar",
},
"type": "required",
"types": {
"required": "must have required property 'bar'",
},
},
"foo": {
"message": "must have required property 'foo'",
"ref": {
"name": "foo",
},
"type": "required",
"types": {
"required": "must have required property 'foo'",
},
},
},
"values": {},
}
`;
exports[`ajvResolver with errorMessage > should return customized errors for properties/items when some properties are undefined 1`] = `
{
"errors": {
"bar": {
"message": "must have required property 'bar'",
"ref": {
"name": "bar",
},
"type": "required",
"types": {
"required": "must have required property 'bar'",
},
},
"foo": {
"message": "must have required property 'foo'",
"ref": {
"name": "foo",
},
"type": "required",
"types": {
"required": "must have required property 'foo'",
},
},
},
"values": {},
}
`;
exports[`ajvResolver with errorMessage > should return customized errors for properties/items when walidation fails 1`] = `
{
"errors": {
"bar": {
"message": "data.bar should be string with length >= 2",
"ref": {
"name": "bar",
},
"type": "minLength",
"types": {
"minLength": "data.bar should be string with length >= 2",
},
},
"foo": {
"message": "data.foo should be integer >= 2",
"ref": {
"name": "foo",
},
"type": "minimum",
"types": {
"minimum": "data.foo should be integer >= 2",
},
},
},
"values": {},
}
`;
exports[`ajvResolver with errorMessage > should return different messages for different properties when requirement fails 1`] = `
{
"errors": {
"bar": {
"message": "should have a string property "bar"",
"ref": {
"name": "bar",
},
"type": "required",
"types": {
"required": "should have a string property "bar"",
},
},
"foo": {
"message": "should have an integer property "foo"",
"ref": {
"name": "foo",
},
"type": "required",
"types": {
"required": "should have an integer property "foo"",
},
},
},
"values": {},
}
`;
exports[`ajvResolver with errorMessage > should return different messages for different properties when some properties are undefined 1`] = `
{
"errors": {
"bar": {
"message": "should have a string property "bar"",
"ref": {
"name": "bar",
},
"type": "required",
"types": {
"required": "should have a string property "bar"",
},
},
"foo": {
"message": "should have an integer property "foo"",
"ref": {
"name": "foo",
},
"type": "required",
"types": {
"required": "should have an integer property "foo"",
},
},
},
"values": {},
}
`;
exports[`ajvResolver with errorMessage > should return different messages for different properties when walidation fails 1`] = `
{
"errors": {
"bar": {
"message": "must be string",
"ref": {
"name": "bar",
},
"type": "type",
"types": {
"type": "must be string",
},
},
"foo": {
"message": "must be integer",
"ref": {
"name": "foo",
},
"type": "type",
"types": {
"type": "must be integer",
},
},
},
"values": {},
}
`;
exports[`ajvResolver with errorMessage > should return the same customized error message when requirement fails 1`] = `
{
"errors": {
"foo": {
"message": "should be an object with an integer property foo only",
"ref": {
"name": "foo",
},
"type": "required",
"types": {
"required": "should be an object with an integer property foo only",
},
},
},
"values": {},
}
`;
exports[`ajvResolver with errorMessage > should return the same customized message for all validation failures 1`] = `
{
"errors": {
"": {
"message": "should be an object with an integer property foo only",
"ref": undefined,
"type": "additionalProperties",
"types": {
"additionalProperties": "should be an object with an integer property foo only",
},
},
"foo": {
"message": "should be an object with an integer property foo only",
"ref": {
"name": "foo",
},
"type": "type",
"types": {
"type": "should be an object with an integer property foo only",
},
},
},
"values": {},
}
`;
exports[`ajvResolver with errorMessage > should return the same customized message when some properties are undefined 1`] = `
{
"errors": {
"foo": {
"message": "should be an object with an integer property foo only",
"ref": {
"name": "foo",
},
"type": "required",
"types": {
"required": "should be an object with an integer property foo only",
},
},
},
"values": {},
}
`;

View file

@ -0,0 +1,245 @@
// Vitest Snapshot v1, https://vitest.dev/guide/snapshot.html
exports[`ajvResolver > should return all the error messages from ajvResolver when requirement fails and validateAllFieldCriteria set to true 1`] = `
{
"errors": {
"deepObject": {
"message": "must have required property 'deepObject'",
"ref": undefined,
"type": "required",
},
"password": {
"message": "must have required property 'password'",
"ref": {
"name": "password",
},
"type": "required",
},
"username": {
"message": "must have required property 'username'",
"ref": {
"name": "username",
},
"type": "required",
},
},
"values": {},
}
`;
exports[`ajvResolver > should return all the error messages from ajvResolver when requirement fails and validateAllFieldCriteria set to true and \`mode: sync\` 1`] = `
{
"errors": {
"deepObject": {
"message": "must have required property 'deepObject'",
"ref": undefined,
"type": "required",
},
"password": {
"message": "must have required property 'password'",
"ref": {
"name": "password",
},
"type": "required",
},
"username": {
"message": "must have required property 'username'",
"ref": {
"name": "username",
},
"type": "required",
},
},
"values": {},
}
`;
exports[`ajvResolver > should return all the error messages from ajvResolver when some property is undefined and result will keep the input data structure 1`] = `
{
"errors": {
"deepObject": {
"data": {
"message": "must have required property 'data'",
"ref": undefined,
"type": "required",
},
},
"password": {
"message": "must have required property 'password'",
"ref": {
"name": "password",
},
"type": "required",
},
},
"values": {},
}
`;
exports[`ajvResolver > should return all the error messages from ajvResolver when validation fails and validateAllFieldCriteria set to true 1`] = `
{
"errors": {
"deepObject": {
"data": {
"message": "must be string",
"ref": undefined,
"type": "type",
"types": {
"type": "must be string",
},
},
"twoLayersDeep": {
"name": {
"message": "must be string",
"ref": undefined,
"type": "type",
"types": {
"type": "must be string",
},
},
},
},
"password": {
"message": "One uppercase character",
"ref": {
"name": "password",
},
"type": "pattern",
"types": {
"pattern": "One uppercase character",
},
},
"username": {
"message": "must NOT have fewer than 3 characters",
"ref": {
"name": "username",
},
"type": "minLength",
"types": {
"minLength": "must NOT have fewer than 3 characters",
},
},
},
"values": {},
}
`;
exports[`ajvResolver > should return all the error messages from ajvResolver when validation fails and validateAllFieldCriteria set to true and \`mode: sync\` 1`] = `
{
"errors": {
"deepObject": {
"data": {
"message": "must be string",
"ref": undefined,
"type": "type",
"types": {
"type": "must be string",
},
},
"twoLayersDeep": {
"name": {
"message": "must be string",
"ref": undefined,
"type": "type",
"types": {
"type": "must be string",
},
},
},
},
"password": {
"message": "One uppercase character",
"ref": {
"name": "password",
},
"type": "pattern",
"types": {
"pattern": "One uppercase character",
},
},
"username": {
"message": "must NOT have fewer than 3 characters",
"ref": {
"name": "username",
},
"type": "minLength",
"types": {
"minLength": "must NOT have fewer than 3 characters",
},
},
},
"values": {},
}
`;
exports[`ajvResolver > should return single error message from ajvResolver when validation fails and validateAllFieldCriteria set to false 1`] = `
{
"errors": {
"deepObject": {
"data": {
"message": "must be string",
"ref": undefined,
"type": "type",
},
"twoLayersDeep": {
"name": {
"message": "must be string",
"ref": undefined,
"type": "type",
},
},
},
"password": {
"message": "One uppercase character",
"ref": {
"name": "password",
},
"type": "pattern",
},
"username": {
"message": "must NOT have fewer than 3 characters",
"ref": {
"name": "username",
},
"type": "minLength",
},
},
"values": {},
}
`;
exports[`ajvResolver > should return single error message from ajvResolver when validation fails and validateAllFieldCriteria set to false and \`mode: sync\` 1`] = `
{
"errors": {
"deepObject": {
"data": {
"message": "must be string",
"ref": undefined,
"type": "type",
},
"twoLayersDeep": {
"name": {
"message": "must be string",
"ref": undefined,
"type": "type",
},
},
},
"password": {
"message": "One uppercase character",
"ref": {
"name": "password",
},
"type": "pattern",
},
"username": {
"message": "must NOT have fewer than 3 characters",
"ref": {
"name": "username",
},
"type": "minLength",
},
},
"values": {},
}
`;

View file

@ -0,0 +1,227 @@
import { ajvResolver } from '..';
import * as fixture from './__fixtures__/data-errors';
const shouldUseNativeValidation = false;
describe('ajvResolver with errorMessage', () => {
it('should return values when validation pass', async () => {
expect(
await ajvResolver(fixture.schemaA)(fixture.validDataA, undefined, {
fields: fixture.fieldsA,
criteriaMode: 'all',
shouldUseNativeValidation,
}),
).toEqual({
values: fixture.validDataA,
errors: {},
});
});
it('should return customized error messages when validation fails', async () => {
expect(
await ajvResolver(fixture.schemaA)(
fixture.invalidDataA,
{},
{
fields: fixture.fieldsA,
criteriaMode: 'all',
shouldUseNativeValidation,
},
),
).toMatchSnapshot();
});
it('should return customized error messages when requirement fails', async () => {
expect(
await ajvResolver(fixture.schemaA)({}, undefined, {
fields: fixture.fieldsA,
criteriaMode: 'all',
shouldUseNativeValidation,
}),
).toMatchSnapshot();
});
it('should return customized error messages when some properties are undefined', async () => {
expect(
await ajvResolver(fixture.schemaA, undefined, { mode: 'sync' })(
fixture.undefinedDataA,
undefined,
{
fields: fixture.fieldsA,
criteriaMode: 'all',
shouldUseNativeValidation,
},
),
).toMatchSnapshot();
});
it('should return the same customized message for all validation failures', async () => {
expect(
await ajvResolver(fixture.schemaB)(
fixture.invalidDataB,
{},
{
fields: fixture.fieldsRest,
criteriaMode: 'all',
shouldUseNativeValidation,
},
),
).toMatchSnapshot();
});
it('should return the same customized error message when requirement fails', async () => {
expect(
await ajvResolver(fixture.schemaB)({}, undefined, {
fields: fixture.fieldsRest,
criteriaMode: 'all',
shouldUseNativeValidation,
}),
).toMatchSnapshot();
});
it('should return the same customized message when some properties are undefined', async () => {
expect(
await ajvResolver(fixture.schemaB)(fixture.undefinedDataB, undefined, {
fields: fixture.fieldsRest,
criteriaMode: 'all',
shouldUseNativeValidation,
}),
).toMatchSnapshot();
});
it('should return customized error messages for certain keywords when walidation fails', async () => {
expect(
await ajvResolver(fixture.schemaC)(
fixture.invalidDataC,
{},
{
fields: fixture.fieldsRest,
criteriaMode: 'all',
shouldUseNativeValidation,
},
),
).toMatchSnapshot();
});
it('should return customized error messages for certain keywords when requirement fails', async () => {
expect(
await ajvResolver(fixture.schemaC)({}, undefined, {
fields: fixture.fieldsRest,
criteriaMode: 'all',
shouldUseNativeValidation,
}),
).toMatchSnapshot();
});
it('should return customized error messages for certain keywords when some properties are undefined', async () => {
expect(
await ajvResolver(fixture.schemaC)(fixture.undefinedDataC, undefined, {
fields: fixture.fieldsRest,
criteriaMode: 'all',
shouldUseNativeValidation,
}),
).toMatchSnapshot();
});
it('should return different messages for different properties when walidation fails', async () => {
expect(
await ajvResolver(fixture.schemaD)(
fixture.invalidDataD,
{},
{
fields: fixture.fieldsRest,
criteriaMode: 'all',
shouldUseNativeValidation,
},
),
).toMatchSnapshot();
});
it('should return different messages for different properties when requirement fails', async () => {
expect(
await ajvResolver(fixture.schemaD)({}, undefined, {
fields: fixture.fieldsRest,
criteriaMode: 'all',
shouldUseNativeValidation,
}),
).toMatchSnapshot();
});
it('should return different messages for different properties when some properties are undefined', async () => {
expect(
await ajvResolver(fixture.schemaD)(fixture.undefinedDataD, undefined, {
fields: fixture.fieldsRest,
criteriaMode: 'all',
shouldUseNativeValidation,
}),
).toMatchSnapshot();
});
it('should return customized errors for properties/items when walidation fails', async () => {
expect(
await ajvResolver(fixture.schemaE)(
fixture.invalidDataE,
{},
{
fields: fixture.fieldsRest,
criteriaMode: 'all',
shouldUseNativeValidation,
},
),
).toMatchSnapshot();
});
it('should return customized errors for properties/items when requirement fails', async () => {
expect(
await ajvResolver(fixture.schemaE)({}, undefined, {
fields: fixture.fieldsRest,
criteriaMode: 'all',
shouldUseNativeValidation,
}),
).toMatchSnapshot();
});
it('should return customized errors for properties/items when some properties are undefined', async () => {
expect(
await ajvResolver(fixture.schemaE)(fixture.undefinedDataE, undefined, {
fields: fixture.fieldsRest,
criteriaMode: 'all',
shouldUseNativeValidation,
}),
).toMatchSnapshot();
});
it('should return a default message if there is no specific message for the error when walidation fails', async () => {
expect(
await ajvResolver(fixture.schemaF)(
fixture.invalidDataF,
{},
{
fields: fixture.fieldsRest,
criteriaMode: 'all',
shouldUseNativeValidation,
},
),
).toMatchSnapshot();
});
it('should return a default message if there is no specific message for the error when requirement fails', async () => {
expect(
await ajvResolver(fixture.schemaF)({}, undefined, {
fields: fixture.fieldsRest,
criteriaMode: 'all',
shouldUseNativeValidation,
}),
).toMatchSnapshot();
});
it('should return a default message if there is no specific message for the error when some properties are undefined', async () => {
expect(
await ajvResolver(fixture.schemaF)(fixture.undefinedDataF, undefined, {
fields: fixture.fieldsRest,
criteriaMode: 'all',
shouldUseNativeValidation,
}),
).toMatchSnapshot();
});
});

View file

@ -0,0 +1,103 @@
import { ajvResolver } from '..';
import {
fields,
invalidData,
invalidDataWithUndefined,
schema,
validData,
} from './__fixtures__/data';
const shouldUseNativeValidation = false;
describe('ajvResolver', () => {
it('should return values from ajvResolver when validation pass', async () => {
expect(
await ajvResolver(schema)(validData, undefined, {
fields,
shouldUseNativeValidation,
}),
).toEqual({
values: validData,
errors: {},
});
});
it('should return values from ajvResolver with `mode: sync` when validation pass', async () => {
expect(
await ajvResolver(schema, undefined, {
mode: 'sync',
})(validData, undefined, { fields, shouldUseNativeValidation }),
).toEqual({
values: validData,
errors: {},
});
});
it('should return single error message from ajvResolver when validation fails and validateAllFieldCriteria set to false', async () => {
expect(
await ajvResolver(schema)(invalidData, undefined, {
fields,
shouldUseNativeValidation,
}),
).toMatchSnapshot();
});
it('should return single error message from ajvResolver when validation fails and validateAllFieldCriteria set to false and `mode: sync`', async () => {
expect(
await ajvResolver(schema, undefined, {
mode: 'sync',
})(invalidData, undefined, { fields, shouldUseNativeValidation }),
).toMatchSnapshot();
});
it('should return all the error messages from ajvResolver when validation fails and validateAllFieldCriteria set to true', async () => {
expect(
await ajvResolver(schema)(
invalidData,
{},
{ fields, criteriaMode: 'all', shouldUseNativeValidation },
),
).toMatchSnapshot();
});
it('should return all the error messages from ajvResolver when validation fails and validateAllFieldCriteria set to true and `mode: sync`', async () => {
expect(
await ajvResolver(schema, undefined, { mode: 'sync' })(
invalidData,
{},
{ fields, criteriaMode: 'all', shouldUseNativeValidation },
),
).toMatchSnapshot();
});
it('should return all the error messages from ajvResolver when requirement fails and validateAllFieldCriteria set to true', async () => {
expect(
await ajvResolver(schema)({}, undefined, {
fields,
shouldUseNativeValidation,
}),
).toMatchSnapshot();
});
it('should return all the error messages from ajvResolver when requirement fails and validateAllFieldCriteria set to true and `mode: sync`', async () => {
expect(
await ajvResolver(schema, undefined, { mode: 'sync' })({}, undefined, {
fields,
shouldUseNativeValidation,
}),
).toMatchSnapshot();
});
it('should return all the error messages from ajvResolver when some property is undefined and result will keep the input data structure', async () => {
expect(
await ajvResolver(schema, undefined, { mode: 'sync' })(
invalidDataWithUndefined,
undefined,
{
fields,
shouldUseNativeValidation,
},
),
).toMatchSnapshot();
});
});

123
node_modules/@hookform/resolvers/ajv/src/ajv.ts generated vendored Normal file
View file

@ -0,0 +1,123 @@
import { toNestErrors, validateFieldsNatively } from '@hookform/resolvers';
import Ajv, { DefinedError } from 'ajv';
import ajvErrors from 'ajv-errors';
import addFormats from 'ajv-formats';
import { FieldError, appendErrors } from 'react-hook-form';
import { AjvError, Resolver } from './types';
const parseErrorSchema = (
ajvErrors: AjvError[],
validateAllFieldCriteria: boolean,
) => {
const parsedErrors: Record<string, FieldError> = {};
const reduceError = (error: AjvError) => {
// Ajv will return empty instancePath when require error
if (error.keyword === 'required') {
error.instancePath += `/${error.params.missingProperty}`;
}
// `/deepObject/data` -> `deepObject.data`
const path = error.instancePath.substring(1).replace(/\//g, '.');
if (!parsedErrors[path]) {
parsedErrors[path] = {
message: error.message,
type: error.keyword,
};
}
if (validateAllFieldCriteria) {
const types = parsedErrors[path].types;
const messages = types && types[error.keyword];
parsedErrors[path] = appendErrors(
path,
validateAllFieldCriteria,
parsedErrors,
error.keyword,
messages
? ([] as string[]).concat(messages as string[], error.message || '')
: error.message,
) as FieldError;
}
};
for (let index = 0; index < ajvErrors.length; index += 1) {
const error = ajvErrors[index];
if (error.keyword === 'errorMessage') {
error.params.errors.forEach((originalError) => {
originalError.message = error.message;
reduceError(originalError);
});
} else {
reduceError(error);
}
}
return parsedErrors;
};
/**
* Creates a resolver for react-hook-form using Ajv schema validation
* @param {Schema} schema - The Ajv schema to validate against
* @param {Object} schemaOptions - Additional schema validation options
* @param {Object} resolverOptions - Additional resolver configuration
* @param {string} [resolverOptions.mode='async'] - Validation mode
* @returns {Resolver<Schema>} A resolver function compatible with react-hook-form
* @example
* const schema = ajv.compile({
* type: 'object',
* properties: {
* name: { type: 'string' },
* age: { type: 'number' }
* }
* });
*
* useForm({
* resolver: ajvResolver(schema)
* });
*/
export const ajvResolver: Resolver =
(schema, schemaOptions, resolverOptions = {}) =>
async (values, _, options) => {
const ajv = new Ajv(
Object.assign(
{},
{
allErrors: true,
validateSchema: true,
},
schemaOptions,
),
);
ajvErrors(ajv);
addFormats(ajv);
const validate = ajv.compile(
Object.assign(
{ $async: resolverOptions && resolverOptions.mode === 'async' },
schema,
),
);
const valid = validate(values);
options.shouldUseNativeValidation && validateFieldsNatively({}, options);
return valid
? { values, errors: {} }
: {
values: {},
errors: toNestErrors(
parseErrorSchema(
validate.errors as DefinedError[],
!options.shouldUseNativeValidation &&
options.criteriaMode === 'all',
),
options,
),
};
};

2
node_modules/@hookform/resolvers/ajv/src/index.ts generated vendored Normal file
View file

@ -0,0 +1,2 @@
export * from './ajv';
export * from './types';

20
node_modules/@hookform/resolvers/ajv/src/types.ts generated vendored Normal file
View file

@ -0,0 +1,20 @@
import * as Ajv from 'ajv';
import type { DefinedError, ErrorObject } from 'ajv';
import { FieldValues, ResolverOptions, ResolverResult } from 'react-hook-form';
export type Resolver = <T>(
schema: Ajv.JSONSchemaType<T>,
schemaOptions?: Ajv.Options,
factoryOptions?: { mode?: 'async' | 'sync' },
) => <TFieldValues extends FieldValues, TContext>(
values: TFieldValues,
context: TContext | undefined,
options: ResolverOptions<TFieldValues>,
) => Promise<ResolverResult<TFieldValues>>;
// ajv doesn't export any types for errors with `keyword='errorMessage'`
type ErrorMessage = ErrorObject<
'errorMessage',
{ errors: (DefinedError & { emUsed: boolean })[] }
>;
export type AjvError = ErrorMessage | DefinedError;

View file

@ -0,0 +1,8 @@
import { StandardSchemaV1 } from '@standard-schema/spec';
import { FieldValues, Resolver } from 'react-hook-form';
export declare function arktypeResolver<Input extends FieldValues, Context, Output>(schema: StandardSchemaV1<Input, Output>, _schemaOptions?: never, resolverOptions?: {
raw?: false;
}): Resolver<Input, Context, Output>;
export declare function arktypeResolver<Input extends FieldValues, Context, Output>(schema: StandardSchemaV1<Input, Output>, _schemaOptions: never | undefined, resolverOptions: {
raw: true;
}): Resolver<Input, Context, Input>;

View file

@ -0,0 +1,2 @@
var e=require("@hookform/resolvers");function r(){return r=Object.assign?Object.assign.bind():function(e){for(var r=1;r<arguments.length;r++){var t=arguments[r];for(var n in t)({}).hasOwnProperty.call(t,n)&&(e[n]=t[n])}return e},r.apply(null,arguments)}function t(e){if(e.path?.length){let r="";for(const t of e.path){const e="object"==typeof t?t.key:t;if("string"!=typeof e&&"number"!=typeof e)return null;r+=r?`.${e}`:e}return r}return null}exports.arktypeResolver=function(n,s,o){return void 0===o&&(o={}),function(s,a,i){try{var u=function(){if(l.issues){var n=function(e,n){for(var s={},o=0;o<e.length;o++){var a=e[o],i=t(a);if(i&&(s[i]||(s[i]={message:a.message,type:""}),n)){var u,l=s[i].types||{};s[i].types=r({},l,((u={})[Object.keys(l).length]=a.message,u))}}return s}(l.issues,!i.shouldUseNativeValidation&&"all"===i.criteriaMode);return{values:{},errors:e.toNestErrors(n,i)}}return i.shouldUseNativeValidation&&e.validateFieldsNatively({},i),{values:o.raw?Object.assign({},s):l.value,errors:{}}},l=n["~standard"].validate(s),f=function(){if(l instanceof Promise)return Promise.resolve(l).then(function(e){l=e})}();return Promise.resolve(f&&f.then?f.then(u):u())}catch(e){return Promise.reject(e)}}};
//# sourceMappingURL=arktype.js.map

File diff suppressed because one or more lines are too long

View file

@ -0,0 +1,2 @@
import{toNestErrors as e,validateFieldsNatively as r}from"@hookform/resolvers";function t(){return t=Object.assign?Object.assign.bind():function(e){for(var r=1;r<arguments.length;r++){var t=arguments[r];for(var n in t)({}).hasOwnProperty.call(t,n)&&(e[n]=t[n])}return e},t.apply(null,arguments)}function n(e){if(e.path?.length){let r="";for(const t of e.path){const e="object"==typeof t?t.key:t;if("string"!=typeof e&&"number"!=typeof e)return null;r+=r?`.${e}`:e}return r}return null}function o(o,s,i){return void 0===i&&(i={}),function(s,a,u){try{var l=function(){if(f.issues){var o=function(e,r){for(var o={},s=0;s<e.length;s++){var i=e[s],a=n(i);if(a&&(o[a]||(o[a]={message:i.message,type:""}),r)){var u,l=o[a].types||{};o[a].types=t({},l,((u={})[Object.keys(l).length]=i.message,u))}}return o}(f.issues,!u.shouldUseNativeValidation&&"all"===u.criteriaMode);return{values:{},errors:e(o,u)}}return u.shouldUseNativeValidation&&r({},u),{values:i.raw?Object.assign({},s):f.value,errors:{}}},f=o["~standard"].validate(s),c=function(){if(f instanceof Promise)return Promise.resolve(f).then(function(e){f=e})}();return Promise.resolve(c&&c.then?c.then(l):l())}catch(e){return Promise.reject(e)}}}export{o as arktypeResolver};
//# sourceMappingURL=arktype.module.js.map

View file

@ -0,0 +1,2 @@
import{toNestErrors as e,validateFieldsNatively as t}from"@hookform/resolvers";function n(){return n=Object.assign?Object.assign.bind():function(e){for(var t=1;t<arguments.length;t++){var n=arguments[t];for(var r in n)({}).hasOwnProperty.call(n,r)&&(e[r]=n[r])}return e},n.apply(null,arguments)}function r(e){if(e.path?.length){let t="";for(const n of e.path){const e="object"==typeof n?n.key:n;if("string"!=typeof e&&"number"!=typeof e)return null;t+=t?`.${e}`:e}return t}return null}function s(s,o,a={}){return async(o,i,l)=>{let u=s["~standard"].validate(o);if(u instanceof Promise&&(u=await u),u.issues){const t=function(e,t){const s={};for(let o=0;o<e.length;o++){const a=e[o],i=r(a);if(i&&(s[i]||(s[i]={message:a.message,type:""}),t)){const e=s[i].types||{};s[i].types=n({},e,{[Object.keys(e).length]:a.message})}}return s}(u.issues,!l.shouldUseNativeValidation&&"all"===l.criteriaMode);return{values:{},errors:e(t,l)}}return l.shouldUseNativeValidation&&t({},l),{values:a.raw?Object.assign({},o):u.value,errors:{}}}}export{s as arktypeResolver};
//# sourceMappingURL=arktype.modern.mjs.map

File diff suppressed because one or more lines are too long

View file

@ -0,0 +1,2 @@
import{toNestErrors as e,validateFieldsNatively as r}from"@hookform/resolvers";function t(){return t=Object.assign?Object.assign.bind():function(e){for(var r=1;r<arguments.length;r++){var t=arguments[r];for(var n in t)({}).hasOwnProperty.call(t,n)&&(e[n]=t[n])}return e},t.apply(null,arguments)}function n(e){if(e.path?.length){let r="";for(const t of e.path){const e="object"==typeof t?t.key:t;if("string"!=typeof e&&"number"!=typeof e)return null;r+=r?`.${e}`:e}return r}return null}function o(o,s,i){return void 0===i&&(i={}),function(s,a,u){try{var l=function(){if(f.issues){var o=function(e,r){for(var o={},s=0;s<e.length;s++){var i=e[s],a=n(i);if(a&&(o[a]||(o[a]={message:i.message,type:""}),r)){var u,l=o[a].types||{};o[a].types=t({},l,((u={})[Object.keys(l).length]=i.message,u))}}return o}(f.issues,!u.shouldUseNativeValidation&&"all"===u.criteriaMode);return{values:{},errors:e(o,u)}}return u.shouldUseNativeValidation&&r({},u),{values:i.raw?Object.assign({},s):f.value,errors:{}}},f=o["~standard"].validate(s),c=function(){if(f instanceof Promise)return Promise.resolve(f).then(function(e){f=e})}();return Promise.resolve(c&&c.then?c.then(l):l())}catch(e){return Promise.reject(e)}}}export{o as arktypeResolver};
//# sourceMappingURL=arktype.module.js.map

File diff suppressed because one or more lines are too long

View file

@ -0,0 +1,2 @@
!function(e,r){"object"==typeof exports&&"undefined"!=typeof module?r(exports,require("@hookform/resolvers")):"function"==typeof define&&define.amd?define(["exports","@hookform/resolvers"],r):r((e||self).hookformResolversArktype={},e.hookformResolvers)}(this,function(e,r){function t(){return t=Object.assign?Object.assign.bind():function(e){for(var r=1;r<arguments.length;r++){var t=arguments[r];for(var o in t)({}).hasOwnProperty.call(t,o)&&(e[o]=t[o])}return e},t.apply(null,arguments)}function o(e){if(e.path?.length){let r="";for(const t of e.path){const e="object"==typeof t?t.key:t;if("string"!=typeof e&&"number"!=typeof e)return null;r+=r?`.${e}`:e}return r}return null}e.arktypeResolver=function(e,n,s){return void 0===s&&(s={}),function(n,i,a){try{var f=function(){if(l.issues){var e=function(e,r){for(var n={},s=0;s<e.length;s++){var i=e[s],a=o(i);if(a&&(n[a]||(n[a]={message:i.message,type:""}),r)){var f,l=n[a].types||{};n[a].types=t({},l,((f={})[Object.keys(l).length]=i.message,f))}}return n}(l.issues,!a.shouldUseNativeValidation&&"all"===a.criteriaMode);return{values:{},errors:r.toNestErrors(e,a)}}return a.shouldUseNativeValidation&&r.validateFieldsNatively({},a),{values:s.raw?Object.assign({},n):l.value,errors:{}}},l=e["~standard"].validate(n),u=function(){if(l instanceof Promise)return Promise.resolve(l).then(function(e){l=e})}();return Promise.resolve(u&&u.then?u.then(f):f())}catch(e){return Promise.reject(e)}}}});
//# sourceMappingURL=arktype.umd.js.map

File diff suppressed because one or more lines are too long

View file

@ -0,0 +1 @@
export * from './arktype';

18
node_modules/@hookform/resolvers/arktype/package.json generated vendored Normal file
View file

@ -0,0 +1,18 @@
{
"name": "@hookform/resolvers/arktype",
"amdName": "hookformResolversArktype",
"version": "2.0.0",
"private": true,
"description": "React Hook Form validation resolver: arktype",
"main": "dist/arktype.js",
"module": "dist/arktype.module.js",
"umd:main": "dist/arktype.umd.js",
"source": "src/index.ts",
"types": "dist/index.d.ts",
"license": "MIT",
"peerDependencies": {
"react-hook-form": "^7.55.0",
"@hookform/resolvers": "^2.0.0",
"arktype": "^2.0.0"
}
}

View file

@ -0,0 +1,82 @@
import { render, screen } from '@testing-library/react';
import user from '@testing-library/user-event';
import { type } from 'arktype';
import React from 'react';
import { useForm } from 'react-hook-form';
import { arktypeResolver } from '..';
const schema = type({
username: 'string>1',
password: 'string>1',
});
type FormData = typeof schema.infer;
interface Props {
onSubmit: (data: FormData) => void;
}
function TestComponent({ onSubmit }: Props) {
const { register, handleSubmit } = useForm<FormData>({
resolver: arktypeResolver(schema),
shouldUseNativeValidation: true,
});
return (
<form onSubmit={handleSubmit(onSubmit)}>
<input {...register('username')} placeholder="username" />
<input {...register('password')} placeholder="password" />
<button type="submit">submit</button>
</form>
);
}
test("form's native validation with Arktype", async () => {
const handleSubmit = vi.fn();
render(<TestComponent onSubmit={handleSubmit} />);
// username
let usernameField = screen.getByPlaceholderText(
/username/i,
) as HTMLInputElement;
expect(usernameField.validity.valid).toBe(true);
expect(usernameField.validationMessage).toBe('');
// password
let passwordField = screen.getByPlaceholderText(
/password/i,
) as HTMLInputElement;
expect(passwordField.validity.valid).toBe(true);
expect(passwordField.validationMessage).toBe('');
await user.click(screen.getByText(/submit/i));
// username
usernameField = screen.getByPlaceholderText(/username/i) as HTMLInputElement;
expect(usernameField.validity.valid).toBe(false);
expect(usernameField.validationMessage).toBe(
'username must be at least length 2',
);
// password
passwordField = screen.getByPlaceholderText(/password/i) as HTMLInputElement;
expect(passwordField.validity.valid).toBe(false);
expect(passwordField.validationMessage).toBe(
'password must be at least length 2',
);
await user.type(screen.getByPlaceholderText(/username/i), 'joe');
await user.type(screen.getByPlaceholderText(/password/i), 'password');
// username
usernameField = screen.getByPlaceholderText(/username/i) as HTMLInputElement;
expect(usernameField.validity.valid).toBe(true);
expect(usernameField.validationMessage).toBe('');
// password
passwordField = screen.getByPlaceholderText(/password/i) as HTMLInputElement;
expect(passwordField.validity.valid).toBe(true);
expect(passwordField.validationMessage).toBe('');
});

View file

@ -0,0 +1,54 @@
import { render, screen } from '@testing-library/react';
import user from '@testing-library/user-event';
import { type } from 'arktype';
import React from 'react';
import { useForm } from 'react-hook-form';
import { arktypeResolver } from '..';
const schema = type({
username: 'string>1',
password: 'string>1',
});
function TestComponent({
onSubmit,
}: {
onSubmit: (data: typeof schema.infer) => void;
}) {
const {
register,
handleSubmit,
formState: { errors },
} = useForm({
resolver: arktypeResolver(schema), // Useful to check TypeScript regressions
});
return (
<form onSubmit={handleSubmit(onSubmit)}>
<input {...register('username')} />
{errors.username && <span role="alert">{errors.username.message}</span>}
<input {...register('password')} />
{errors.password && <span role="alert">{errors.password.message}</span>}
<button type="submit">submit</button>
</form>
);
}
test("form's validation with arkType and TypeScript's integration", async () => {
const handleSubmit = vi.fn();
render(<TestComponent onSubmit={handleSubmit} />);
expect(screen.queryAllByRole('alert')).toHaveLength(0);
await user.click(screen.getByText(/submit/i));
expect(
screen.getByText('username must be at least length 2'),
).toBeInTheDocument();
expect(
screen.getByText('password must be at least length 2'),
).toBeInTheDocument();
expect(handleSubmit).not.toHaveBeenCalled();
});

View file

@ -0,0 +1,65 @@
import { type } from 'arktype';
import { Field, InternalFieldName } from 'react-hook-form';
export const schema = type({
username: 'string>2',
password: '/.*[A-Za-z].*/>8|/.*\\d.*/',
repeatPassword: 'string>1',
accessToken: 'string|number',
birthYear: '1900<number<2013',
email: 'string.email',
tags: 'string[]',
enabled: 'boolean',
url: 'string>1',
'like?': type({
id: 'number',
name: 'string>3',
}).array(),
dateStr: 'Date',
});
export const validData: typeof schema.infer = {
username: 'Doe',
password: 'Password123_',
repeatPassword: 'Password123_',
birthYear: 2000,
email: 'john@doe.com',
tags: ['tag1', 'tag2'],
enabled: true,
accessToken: 'accessToken',
url: 'https://react-hook-form.com/',
like: [
{
id: 1,
name: 'name',
},
],
dateStr: new Date('2020-01-01'),
};
export const invalidData = {
password: '___',
email: '',
birthYear: 'birthYear',
like: [{ id: 'z' }],
url: 'abc',
} as any as typeof schema.infer;
export const fields: Record<InternalFieldName, Field['_f']> = {
username: {
ref: { name: 'username' },
name: 'username',
},
password: {
ref: { name: 'password' },
name: 'password',
},
email: {
ref: { name: 'email' },
name: 'email',
},
birthday: {
ref: { name: 'birthday' },
name: 'birthday',
},
};

View file

@ -0,0 +1,74 @@
// Vitest Snapshot v1, https://vitest.dev/guide/snapshot.html
exports[`arktypeResolver > should return a single error from arktypeResolver when validation fails 1`] = `
{
"errors": {
"accessToken": {
"message": "accessToken must be a number or a string (was missing)",
"ref": undefined,
"type": "required",
},
"birthYear": {
"message": "birthYear must be a number (was a string)",
"ref": undefined,
"type": "domain",
},
"dateStr": {
"message": "dateStr must be a Date (was missing)",
"ref": undefined,
"type": "required",
},
"email": {
"message": "email must be an email address (was "")",
"ref": {
"name": "email",
},
"type": "pattern",
},
"enabled": {
"message": "enabled must be boolean (was missing)",
"ref": undefined,
"type": "required",
},
"like": [
{
"id": {
"message": "like[0].id must be a number (was a string)",
"ref": undefined,
"type": "domain",
},
"name": {
"message": "like[0].name must be a string (was missing)",
"ref": undefined,
"type": "required",
},
},
],
"password": {
"message": "password must be matched by .*[A-Za-z].* or matched by .*\\d.* (was "___")",
"ref": {
"name": "password",
},
"type": "union",
},
"repeatPassword": {
"message": "repeatPassword must be a string (was missing)",
"ref": undefined,
"type": "required",
},
"tags": {
"message": "tags must be an array (was missing)",
"ref": undefined,
"type": "required",
},
"username": {
"message": "username must be a string (was missing)",
"ref": {
"name": "username",
},
"type": "required",
},
},
"values": {},
}
`;

View file

@ -0,0 +1,82 @@
import { type } from 'arktype';
import { Resolver, useForm } from 'react-hook-form';
import { SubmitHandler } from 'react-hook-form';
import { arktypeResolver } from '..';
import { fields, invalidData, schema, validData } from './__fixtures__/data';
const shouldUseNativeValidation = false;
describe('arktypeResolver', () => {
it('should return values from arktypeResolver when validation pass & raw=true', async () => {
const result = await arktypeResolver(schema, undefined, {
raw: true,
})(validData, undefined, {
fields,
shouldUseNativeValidation,
});
expect(result).toEqual({ errors: {}, values: validData });
});
it('should return a single error from arktypeResolver when validation fails', async () => {
const result = await arktypeResolver(schema)(invalidData, undefined, {
fields,
shouldUseNativeValidation,
});
expect(result).toMatchSnapshot();
});
/**
* Type inference tests
*/
it('should correctly infer the output type from a arktype schema', () => {
const resolver = arktypeResolver(type({ id: 'number' }));
expectTypeOf(resolver).toEqualTypeOf<
Resolver<{ id: number }, unknown, { id: number }>
>();
});
it('should correctly infer the output type from a arktype schema using a transform', () => {
const resolver = arktypeResolver(
type({ id: type('string').pipe((s) => Number.parseInt(s)) }),
);
expectTypeOf(resolver).toEqualTypeOf<
Resolver<{ id: string }, unknown, { id: number }>
>();
});
it('should correctly infer the output type from a arktype schema for the handleSubmit function in useForm', () => {
const schema = type({ id: 'number' });
const form = useForm({
resolver: arktypeResolver(schema),
});
expectTypeOf(form.watch('id')).toEqualTypeOf<number>();
expectTypeOf(form.handleSubmit).parameter(0).toEqualTypeOf<
SubmitHandler<{
id: number;
}>
>();
});
it('should correctly infer the output type from a arktype schema with a transform for the handleSubmit function in useForm', () => {
const schema = type({ id: type('string').pipe((s) => Number.parseInt(s)) });
const form = useForm({
resolver: arktypeResolver(schema),
});
expectTypeOf(form.watch('id')).toEqualTypeOf<string>();
expectTypeOf(form.handleSubmit).parameter(0).toEqualTypeOf<
SubmitHandler<{
id: number;
}>
>();
});
});

View file

@ -0,0 +1,98 @@
import { toNestErrors, validateFieldsNatively } from '@hookform/resolvers';
import { StandardSchemaV1 } from '@standard-schema/spec';
import { getDotPath } from '@standard-schema/utils';
import { FieldError, FieldValues, Resolver } from 'react-hook-form';
function parseErrorSchema(
issues: readonly StandardSchemaV1.Issue[],
validateAllFieldCriteria: boolean,
) {
const errors: Record<string, FieldError> = {};
for (let i = 0; i < issues.length; i++) {
const error = issues[i];
const path = getDotPath(error);
if (path) {
if (!errors[path]) {
errors[path] = { message: error.message, type: '' };
}
if (validateAllFieldCriteria) {
const types = errors[path].types || {};
errors[path].types = {
...types,
[Object.keys(types).length]: error.message,
};
}
}
}
return errors;
}
export function arktypeResolver<Input extends FieldValues, Context, Output>(
schema: StandardSchemaV1<Input, Output>,
_schemaOptions?: never,
resolverOptions?: {
raw?: false;
},
): Resolver<Input, Context, Output>;
export function arktypeResolver<Input extends FieldValues, Context, Output>(
schema: StandardSchemaV1<Input, Output>,
_schemaOptions: never | undefined,
resolverOptions: {
raw: true;
},
): Resolver<Input, Context, Input>;
/**
* Creates a resolver for react-hook-form using Arktype schema validation
* @param {Schema} schema - The Arktype schema to validate against
* @param {Object} resolverOptions - Additional resolver configuration
* @param {string} [resolverOptions.mode='raw'] - Return the raw input values rather than the parsed values
* @returns {Resolver<Schema['inferOut']>} A resolver function compatible with react-hook-form
* @example
* const schema = type({
* username: 'string>2'
* });
*
* useForm({
* resolver: arktypeResolver(schema)
* });
*/
export function arktypeResolver<Input extends FieldValues, Context, Output>(
schema: StandardSchemaV1<Input, Output>,
_schemaOptions?: never,
resolverOptions: {
raw?: boolean;
} = {},
): Resolver<Input, Context, Input | Output> {
return async (values: Input, _, options) => {
let result = schema['~standard'].validate(values);
if (result instanceof Promise) {
result = await result;
}
if (result.issues) {
const errors = parseErrorSchema(
result.issues,
!options.shouldUseNativeValidation && options.criteriaMode === 'all',
);
return {
values: {},
errors: toNestErrors(errors, options),
};
}
options.shouldUseNativeValidation && validateFieldsNatively({}, options);
return {
values: resolverOptions.raw ? Object.assign({}, values) : result.value,
errors: {},
};
};
}

View file

@ -0,0 +1 @@
export * from './arktype';

View file

@ -0,0 +1,29 @@
import { ClassConstructor, ClassTransformOptions } from 'class-transformer';
import { ValidatorOptions } from 'class-validator';
import { Resolver } from 'react-hook-form';
/**
* Creates a resolver for react-hook-form using class-validator schema validation
* @param {ClassConstructor<Schema>} schema - The class-validator schema to validate against
* @param {Object} schemaOptions - Additional schema validation options
* @param {Object} resolverOptions - Additional resolver configuration
* @param {string} [resolverOptions.mode='async'] - Validation mode
* @returns {Resolver<Schema>} A resolver function compatible with react-hook-form
* @example
* class Schema {
* @Matches(/^\w+$/)
* @Length(3, 30)
* username: string;
* age: number
* }
*
* useForm({
* resolver: classValidatorResolver(Schema)
* });
*/
export declare function classValidatorResolver<Schema extends Record<string, any>>(schema: ClassConstructor<Schema>, schemaOptions?: {
validator?: ValidatorOptions;
transformer?: ClassTransformOptions;
}, resolverOptions?: {
mode?: 'async' | 'sync';
raw?: boolean;
}): Resolver<Schema>;

View file

@ -0,0 +1,2 @@
var r=require("@hookform/resolvers"),e=require("class-transformer"),t=require("class-validator");function s(r,e,t,a){return void 0===t&&(t={}),void 0===a&&(a=""),r.reduce(function(r,t){var i=a?a+"."+t.property:t.property;if(t.constraints){var o=Object.keys(t.constraints)[0];r[i]={type:o,message:t.constraints[o]};var n=r[i];e&&n&&Object.assign(n,{types:t.constraints})}return t.children&&t.children.length&&s(t.children,e,r,i),r},t)}exports.classValidatorResolver=function(a,i,o){return void 0===i&&(i={}),void 0===o&&(o={}),function(n,l,c){try{var v=i.validator,d=e.plainToClass(a,n,i.transformer);return Promise.resolve(("sync"===o.mode?t.validateSync:t.validate)(d,v)).then(function(e){return e.length?{values:{},errors:r.toNestErrors(s(e,!c.shouldUseNativeValidation&&"all"===c.criteriaMode),c)}:(c.shouldUseNativeValidation&&r.validateFieldsNatively({},c),{values:o.raw?Object.assign({},n):d,errors:{}})})}catch(r){return Promise.reject(r)}}};
//# sourceMappingURL=class-validator.js.map

View file

@ -0,0 +1 @@
{"version":3,"file":"class-validator.js","sources":["../src/class-validator.ts"],"sourcesContent":["import { toNestErrors, validateFieldsNatively } from '@hookform/resolvers';\nimport {\n ClassConstructor,\n ClassTransformOptions,\n plainToClass,\n} from 'class-transformer';\nimport {\n ValidationError,\n ValidatorOptions,\n validate,\n validateSync,\n} from 'class-validator';\nimport { FieldErrors, Resolver } from 'react-hook-form';\n\nfunction parseErrorSchema(\n errors: ValidationError[],\n validateAllFieldCriteria: boolean,\n parsedErrors: FieldErrors = {},\n path = '',\n) {\n return errors.reduce((acc, error) => {\n const _path = path ? `${path}.${error.property}` : error.property;\n\n if (error.constraints) {\n const key = Object.keys(error.constraints)[0];\n acc[_path] = {\n type: key,\n message: error.constraints[key],\n };\n\n const _e = acc[_path];\n if (validateAllFieldCriteria && _e) {\n Object.assign(_e, { types: error.constraints });\n }\n }\n\n if (error.children && error.children.length) {\n parseErrorSchema(error.children, validateAllFieldCriteria, acc, _path);\n }\n\n return acc;\n }, parsedErrors);\n}\n\n/**\n * Creates a resolver for react-hook-form using class-validator schema validation\n * @param {ClassConstructor<Schema>} schema - The class-validator schema to validate against\n * @param {Object} schemaOptions - Additional schema validation options\n * @param {Object} resolverOptions - Additional resolver configuration\n * @param {string} [resolverOptions.mode='async'] - Validation mode\n * @returns {Resolver<Schema>} A resolver function compatible with react-hook-form\n * @example\n * class Schema {\n * @Matches(/^\\w+$/)\n * @Length(3, 30)\n * username: string;\n * age: number\n * }\n *\n * useForm({\n * resolver: classValidatorResolver(Schema)\n * });\n */\nexport function classValidatorResolver<Schema extends Record<string, any>>(\n schema: ClassConstructor<Schema>,\n schemaOptions: {\n validator?: ValidatorOptions;\n transformer?: ClassTransformOptions;\n } = {},\n resolverOptions: { mode?: 'async' | 'sync'; raw?: boolean } = {},\n): Resolver<Schema> {\n return async (values, _, options) => {\n const { transformer, validator } = schemaOptions;\n const data = plainToClass(schema, values, transformer);\n\n const rawErrors = await (resolverOptions.mode === 'sync'\n ? validateSync\n : validate)(data, validator);\n\n if (rawErrors.length) {\n return {\n values: {},\n errors: toNestErrors(\n parseErrorSchema(\n rawErrors,\n !options.shouldUseNativeValidation &&\n options.criteriaMode === 'all',\n ),\n options,\n ),\n };\n }\n\n options.shouldUseNativeValidation && validateFieldsNatively({}, options);\n\n return {\n values: resolverOptions.raw ? Object.assign({}, values) : data,\n errors: {},\n };\n };\n}\n"],"names":["parseErrorSchema","errors","validateAllFieldCriteria","parsedErrors","path","reduce","acc","error","_path","property","constraints","key","Object","keys","type","message","_e","assign","types","children","length","schema","schemaOptions","resolverOptions","values","_","options","validator","data","plainToClass","transformer","Promise","resolve","mode","validateSync","validate","then","rawErrors","toNestErrors","shouldUseNativeValidation","criteriaMode","validateFieldsNatively","raw","e","reject"],"mappings":"iGAcA,SAASA,EACPC,EACAC,EACAC,EACAC,GAEA,YAHA,IAAAD,IAAAA,EAA4B,CAAE,YAC9BC,IAAAA,EAAO,IAEAH,EAAOI,OAAO,SAACC,EAAKC,GACzB,IAAMC,EAAQJ,EAAUA,EAAI,IAAIG,EAAME,SAAaF,EAAME,SAEzD,GAAIF,EAAMG,YAAa,CACrB,IAAMC,EAAMC,OAAOC,KAAKN,EAAMG,aAAa,GAC3CJ,EAAIE,GAAS,CACXM,KAAMH,EACNI,QAASR,EAAMG,YAAYC,IAG7B,IAAMK,EAAKV,EAAIE,GACXN,GAA4Bc,GAC9BJ,OAAOK,OAAOD,EAAI,CAAEE,MAAOX,EAAMG,aAErC,CAMA,OAJIH,EAAMY,UAAYZ,EAAMY,SAASC,QACnCpB,EAAiBO,EAAMY,SAAUjB,EAA0BI,EAAKE,GAG3DF,CACT,EAAGH,EACL,gCAqBM,SACJkB,EACAC,EAIAC,GAEA,gBANAD,IAAAA,EAGI,CAAE,QACN,IAAAC,IAAAA,EAA8D,CAAE,GAEhE,SAAcC,EAAQC,EAAGC,OACvB,IAAqBC,EAAcL,EAAdK,UACfC,EAAOC,EAAYA,aAACR,EAAQG,EADCF,EAA3BQ,aAC+C,OAAAC,QAAAC,SAEL,SAAzBT,EAAgBU,KACrCC,eACAC,EAAAA,UAAUP,EAAMD,IAAUS,KAFxBC,SAAAA,GAIN,OAAIA,EAAUjB,OACL,CACLI,OAAQ,CAAA,EACRvB,OAAQqC,eACNtC,EACEqC,GACCX,EAAQa,2BACkB,QAAzBb,EAAQc,cAEZd,KAKNA,EAAQa,2BAA6BE,EAAsBA,uBAAC,CAAE,EAAEf,GAEzD,CACLF,OAAQD,EAAgBmB,IAAM9B,OAAOK,OAAO,CAAE,EAAEO,GAAUI,EAC1D3B,OAAQ,CAAA,GACR,EACJ,CAAC,MAAA0C,GAAAZ,OAAAA,QAAAa,OAAAD,EACH,CAAA,CAAA"}

View file

@ -0,0 +1,2 @@
import{toNestErrors as r,validateFieldsNatively as e}from"@hookform/resolvers";import{plainToClass as t}from"class-transformer";import{validateSync as o,validate as n}from"class-validator";function s(r,e,t,o){return void 0===t&&(t={}),void 0===o&&(o=""),r.reduce(function(r,t){var n=o?o+"."+t.property:t.property;if(t.constraints){var i=Object.keys(t.constraints)[0];r[n]={type:i,message:t.constraints[i]};var a=r[n];e&&a&&Object.assign(a,{types:t.constraints})}return t.children&&t.children.length&&s(t.children,e,r,n),r},t)}function i(i,a,c){return void 0===a&&(a={}),void 0===c&&(c={}),function(l,d,u){try{var v=a.validator,m=t(i,l,a.transformer);return Promise.resolve(("sync"===c.mode?o:n)(m,v)).then(function(t){return t.length?{values:{},errors:r(s(t,!u.shouldUseNativeValidation&&"all"===u.criteriaMode),u)}:(u.shouldUseNativeValidation&&e({},u),{values:c.raw?Object.assign({},l):m,errors:{}})})}catch(r){return Promise.reject(r)}}}export{i as classValidatorResolver};
//# sourceMappingURL=class-validator.module.js.map

View file

@ -0,0 +1,2 @@
import{toNestErrors as r,validateFieldsNatively as t}from"@hookform/resolvers";import{plainToClass as s}from"class-transformer";import{validateSync as e,validate as o}from"class-validator";function n(r,t,s={},e=""){return r.reduce((r,s)=>{const o=e?`${e}.${s.property}`:s.property;if(s.constraints){const e=Object.keys(s.constraints)[0];r[o]={type:e,message:s.constraints[e]};const n=r[o];t&&n&&Object.assign(n,{types:s.constraints})}return s.children&&s.children.length&&n(s.children,t,r,o),r},s)}function a(a,i={},c={}){return async(l,d,m)=>{const{transformer:u,validator:p}=i,f=s(a,l,u),h=await("sync"===c.mode?e:o)(f,p);return h.length?{values:{},errors:r(n(h,!m.shouldUseNativeValidation&&"all"===m.criteriaMode),m)}:(m.shouldUseNativeValidation&&t({},m),{values:c.raw?Object.assign({},l):f,errors:{}})}}export{a as classValidatorResolver};
//# sourceMappingURL=class-validator.modern.mjs.map

View file

@ -0,0 +1 @@
{"version":3,"file":"class-validator.modern.mjs","sources":["../src/class-validator.ts"],"sourcesContent":["import { toNestErrors, validateFieldsNatively } from '@hookform/resolvers';\nimport {\n ClassConstructor,\n ClassTransformOptions,\n plainToClass,\n} from 'class-transformer';\nimport {\n ValidationError,\n ValidatorOptions,\n validate,\n validateSync,\n} from 'class-validator';\nimport { FieldErrors, Resolver } from 'react-hook-form';\n\nfunction parseErrorSchema(\n errors: ValidationError[],\n validateAllFieldCriteria: boolean,\n parsedErrors: FieldErrors = {},\n path = '',\n) {\n return errors.reduce((acc, error) => {\n const _path = path ? `${path}.${error.property}` : error.property;\n\n if (error.constraints) {\n const key = Object.keys(error.constraints)[0];\n acc[_path] = {\n type: key,\n message: error.constraints[key],\n };\n\n const _e = acc[_path];\n if (validateAllFieldCriteria && _e) {\n Object.assign(_e, { types: error.constraints });\n }\n }\n\n if (error.children && error.children.length) {\n parseErrorSchema(error.children, validateAllFieldCriteria, acc, _path);\n }\n\n return acc;\n }, parsedErrors);\n}\n\n/**\n * Creates a resolver for react-hook-form using class-validator schema validation\n * @param {ClassConstructor<Schema>} schema - The class-validator schema to validate against\n * @param {Object} schemaOptions - Additional schema validation options\n * @param {Object} resolverOptions - Additional resolver configuration\n * @param {string} [resolverOptions.mode='async'] - Validation mode\n * @returns {Resolver<Schema>} A resolver function compatible with react-hook-form\n * @example\n * class Schema {\n * @Matches(/^\\w+$/)\n * @Length(3, 30)\n * username: string;\n * age: number\n * }\n *\n * useForm({\n * resolver: classValidatorResolver(Schema)\n * });\n */\nexport function classValidatorResolver<Schema extends Record<string, any>>(\n schema: ClassConstructor<Schema>,\n schemaOptions: {\n validator?: ValidatorOptions;\n transformer?: ClassTransformOptions;\n } = {},\n resolverOptions: { mode?: 'async' | 'sync'; raw?: boolean } = {},\n): Resolver<Schema> {\n return async (values, _, options) => {\n const { transformer, validator } = schemaOptions;\n const data = plainToClass(schema, values, transformer);\n\n const rawErrors = await (resolverOptions.mode === 'sync'\n ? validateSync\n : validate)(data, validator);\n\n if (rawErrors.length) {\n return {\n values: {},\n errors: toNestErrors(\n parseErrorSchema(\n rawErrors,\n !options.shouldUseNativeValidation &&\n options.criteriaMode === 'all',\n ),\n options,\n ),\n };\n }\n\n options.shouldUseNativeValidation && validateFieldsNatively({}, options);\n\n return {\n values: resolverOptions.raw ? Object.assign({}, values) : data,\n errors: {},\n };\n };\n}\n"],"names":["parseErrorSchema","errors","validateAllFieldCriteria","parsedErrors","path","reduce","acc","error","_path","property","constraints","key","Object","keys","type","message","_e","assign","types","children","length","classValidatorResolver","schema","schemaOptions","resolverOptions","values","_","options","transformer","validator","data","plainToClass","rawErrors","mode","validateSync","validate","toNestErrors","shouldUseNativeValidation","criteriaMode","validateFieldsNatively","raw"],"mappings":"6LAcA,SAASA,EACPC,EACAC,EACAC,EAA4B,CAAA,EAC5BC,EAAO,IAEP,OAAOH,EAAOI,OAAO,CAACC,EAAKC,KACzB,MAAMC,EAAQJ,EAAO,GAAGA,KAAQG,EAAME,WAAaF,EAAME,SAEzD,GAAIF,EAAMG,YAAa,CACrB,MAAMC,EAAMC,OAAOC,KAAKN,EAAMG,aAAa,GAC3CJ,EAAIE,GAAS,CACXM,KAAMH,EACNI,QAASR,EAAMG,YAAYC,IAG7B,MAAMK,EAAKV,EAAIE,GACXN,GAA4Bc,GAC9BJ,OAAOK,OAAOD,EAAI,CAAEE,MAAOX,EAAMG,aAErC,CAMA,OAJIH,EAAMY,UAAYZ,EAAMY,SAASC,QACnCpB,EAAiBO,EAAMY,SAAUjB,EAA0BI,EAAKE,GAG3DF,GACNH,EACL,CAqBgB,SAAAkB,EACdC,EACAC,EAGI,GACJC,EAA8D,CAAA,GAE9D,OAAcC,MAAAA,EAAQC,EAAGC,KACvB,MAAMC,YAAEA,EAAWC,UAAEA,GAAcN,EAC7BO,EAAOC,EAAaT,EAAQG,EAAQG,GAEpCI,QAA4C,SAAzBR,EAAgBS,KACrCC,EACAC,GAAUL,EAAMD,GAEpB,OAAIG,EAAUZ,OACL,CACLK,OAAQ,CAAA,EACRxB,OAAQmC,EACNpC,EACEgC,GACCL,EAAQU,2BACkB,QAAzBV,EAAQW,cAEZX,KAKNA,EAAQU,2BAA6BE,EAAuB,GAAIZ,GAEzD,CACLF,OAAQD,EAAgBgB,IAAM5B,OAAOK,OAAO,CAAA,EAAIQ,GAAUK,EAC1D7B,OAAQ,CAAA,IAGd"}

View file

@ -0,0 +1,2 @@
import{toNestErrors as r,validateFieldsNatively as e}from"@hookform/resolvers";import{plainToClass as t}from"class-transformer";import{validateSync as o,validate as n}from"class-validator";function s(r,e,t,o){return void 0===t&&(t={}),void 0===o&&(o=""),r.reduce(function(r,t){var n=o?o+"."+t.property:t.property;if(t.constraints){var i=Object.keys(t.constraints)[0];r[n]={type:i,message:t.constraints[i]};var a=r[n];e&&a&&Object.assign(a,{types:t.constraints})}return t.children&&t.children.length&&s(t.children,e,r,n),r},t)}function i(i,a,c){return void 0===a&&(a={}),void 0===c&&(c={}),function(l,d,u){try{var v=a.validator,m=t(i,l,a.transformer);return Promise.resolve(("sync"===c.mode?o:n)(m,v)).then(function(t){return t.length?{values:{},errors:r(s(t,!u.shouldUseNativeValidation&&"all"===u.criteriaMode),u)}:(u.shouldUseNativeValidation&&e({},u),{values:c.raw?Object.assign({},l):m,errors:{}})})}catch(r){return Promise.reject(r)}}}export{i as classValidatorResolver};
//# sourceMappingURL=class-validator.module.js.map

View file

@ -0,0 +1 @@
{"version":3,"file":"class-validator.module.js","sources":["../src/class-validator.ts"],"sourcesContent":["import { toNestErrors, validateFieldsNatively } from '@hookform/resolvers';\nimport {\n ClassConstructor,\n ClassTransformOptions,\n plainToClass,\n} from 'class-transformer';\nimport {\n ValidationError,\n ValidatorOptions,\n validate,\n validateSync,\n} from 'class-validator';\nimport { FieldErrors, Resolver } from 'react-hook-form';\n\nfunction parseErrorSchema(\n errors: ValidationError[],\n validateAllFieldCriteria: boolean,\n parsedErrors: FieldErrors = {},\n path = '',\n) {\n return errors.reduce((acc, error) => {\n const _path = path ? `${path}.${error.property}` : error.property;\n\n if (error.constraints) {\n const key = Object.keys(error.constraints)[0];\n acc[_path] = {\n type: key,\n message: error.constraints[key],\n };\n\n const _e = acc[_path];\n if (validateAllFieldCriteria && _e) {\n Object.assign(_e, { types: error.constraints });\n }\n }\n\n if (error.children && error.children.length) {\n parseErrorSchema(error.children, validateAllFieldCriteria, acc, _path);\n }\n\n return acc;\n }, parsedErrors);\n}\n\n/**\n * Creates a resolver for react-hook-form using class-validator schema validation\n * @param {ClassConstructor<Schema>} schema - The class-validator schema to validate against\n * @param {Object} schemaOptions - Additional schema validation options\n * @param {Object} resolverOptions - Additional resolver configuration\n * @param {string} [resolverOptions.mode='async'] - Validation mode\n * @returns {Resolver<Schema>} A resolver function compatible with react-hook-form\n * @example\n * class Schema {\n * @Matches(/^\\w+$/)\n * @Length(3, 30)\n * username: string;\n * age: number\n * }\n *\n * useForm({\n * resolver: classValidatorResolver(Schema)\n * });\n */\nexport function classValidatorResolver<Schema extends Record<string, any>>(\n schema: ClassConstructor<Schema>,\n schemaOptions: {\n validator?: ValidatorOptions;\n transformer?: ClassTransformOptions;\n } = {},\n resolverOptions: { mode?: 'async' | 'sync'; raw?: boolean } = {},\n): Resolver<Schema> {\n return async (values, _, options) => {\n const { transformer, validator } = schemaOptions;\n const data = plainToClass(schema, values, transformer);\n\n const rawErrors = await (resolverOptions.mode === 'sync'\n ? validateSync\n : validate)(data, validator);\n\n if (rawErrors.length) {\n return {\n values: {},\n errors: toNestErrors(\n parseErrorSchema(\n rawErrors,\n !options.shouldUseNativeValidation &&\n options.criteriaMode === 'all',\n ),\n options,\n ),\n };\n }\n\n options.shouldUseNativeValidation && validateFieldsNatively({}, options);\n\n return {\n values: resolverOptions.raw ? Object.assign({}, values) : data,\n errors: {},\n };\n };\n}\n"],"names":["parseErrorSchema","errors","validateAllFieldCriteria","parsedErrors","path","reduce","acc","error","_path","property","constraints","key","Object","keys","type","message","_e","assign","types","children","length","classValidatorResolver","schema","schemaOptions","resolverOptions","values","_","options","validator","data","plainToClass","transformer","Promise","resolve","mode","validateSync","validate","then","rawErrors","toNestErrors","shouldUseNativeValidation","criteriaMode","validateFieldsNatively","raw","e","reject"],"mappings":"6LAcA,SAASA,EACPC,EACAC,EACAC,EACAC,GAEA,YAHA,IAAAD,IAAAA,EAA4B,CAAE,YAC9BC,IAAAA,EAAO,IAEAH,EAAOI,OAAO,SAACC,EAAKC,GACzB,IAAMC,EAAQJ,EAAUA,EAAI,IAAIG,EAAME,SAAaF,EAAME,SAEzD,GAAIF,EAAMG,YAAa,CACrB,IAAMC,EAAMC,OAAOC,KAAKN,EAAMG,aAAa,GAC3CJ,EAAIE,GAAS,CACXM,KAAMH,EACNI,QAASR,EAAMG,YAAYC,IAG7B,IAAMK,EAAKV,EAAIE,GACXN,GAA4Bc,GAC9BJ,OAAOK,OAAOD,EAAI,CAAEE,MAAOX,EAAMG,aAErC,CAMA,OAJIH,EAAMY,UAAYZ,EAAMY,SAASC,QACnCpB,EAAiBO,EAAMY,SAAUjB,EAA0BI,EAAKE,GAG3DF,CACT,EAAGH,EACL,CAqBM,SAAUkB,EACdC,EACAC,EAIAC,GAEA,gBANAD,IAAAA,EAGI,CAAE,QACN,IAAAC,IAAAA,EAA8D,CAAE,GAEhE,SAAcC,EAAQC,EAAGC,OACvB,IAAqBC,EAAcL,EAAdK,UACfC,EAAOC,EAAaR,EAAQG,EADCF,EAA3BQ,aAC+C,OAAAC,QAAAC,SAEL,SAAzBT,EAAgBU,KACrCC,EACAC,GAAUP,EAAMD,IAAUS,KAFxBC,SAAAA,GAIN,OAAIA,EAAUlB,OACL,CACLK,OAAQ,CAAA,EACRxB,OAAQsC,EACNvC,EACEsC,GACCX,EAAQa,2BACkB,QAAzBb,EAAQc,cAEZd,KAKNA,EAAQa,2BAA6BE,EAAuB,CAAE,EAAEf,GAEzD,CACLF,OAAQD,EAAgBmB,IAAM/B,OAAOK,OAAO,CAAE,EAAEQ,GAAUI,EAC1D5B,OAAQ,CAAA,GACR,EACJ,CAAC,MAAA2C,GAAAZ,OAAAA,QAAAa,OAAAD,EACH,CAAA,CAAA"}

View file

@ -0,0 +1,2 @@
!function(e,r){"object"==typeof exports&&"undefined"!=typeof module?r(exports,require("@hookform/resolvers"),require("class-transformer"),require("class-validator")):"function"==typeof define&&define.amd?define(["exports","@hookform/resolvers","class-transformer","class-validator"],r):r((e||self).hookformResolversClassValidator={},e.hookformResolvers,e.classTransformer,e.classValidator)}(this,function(e,r,o,s){function t(e,r,o,s){return void 0===o&&(o={}),void 0===s&&(s=""),e.reduce(function(e,o){var a=s?s+"."+o.property:o.property;if(o.constraints){var i=Object.keys(o.constraints)[0];e[a]={type:i,message:o.constraints[i]};var n=e[a];r&&n&&Object.assign(n,{types:o.constraints})}return o.children&&o.children.length&&t(o.children,r,e,a),e},o)}e.classValidatorResolver=function(e,a,i){return void 0===a&&(a={}),void 0===i&&(i={}),function(n,l,c){try{var d=a.validator,f=o.plainToClass(e,n,a.transformer);return Promise.resolve(("sync"===i.mode?s.validateSync:s.validate)(f,d)).then(function(e){return e.length?{values:{},errors:r.toNestErrors(t(e,!c.shouldUseNativeValidation&&"all"===c.criteriaMode),c)}:(c.shouldUseNativeValidation&&r.validateFieldsNatively({},c),{values:i.raw?Object.assign({},n):f,errors:{}})})}catch(e){return Promise.reject(e)}}}});
//# sourceMappingURL=class-validator.umd.js.map

View file

@ -0,0 +1 @@
{"version":3,"file":"class-validator.umd.js","sources":["../src/class-validator.ts"],"sourcesContent":["import { toNestErrors, validateFieldsNatively } from '@hookform/resolvers';\nimport {\n ClassConstructor,\n ClassTransformOptions,\n plainToClass,\n} from 'class-transformer';\nimport {\n ValidationError,\n ValidatorOptions,\n validate,\n validateSync,\n} from 'class-validator';\nimport { FieldErrors, Resolver } from 'react-hook-form';\n\nfunction parseErrorSchema(\n errors: ValidationError[],\n validateAllFieldCriteria: boolean,\n parsedErrors: FieldErrors = {},\n path = '',\n) {\n return errors.reduce((acc, error) => {\n const _path = path ? `${path}.${error.property}` : error.property;\n\n if (error.constraints) {\n const key = Object.keys(error.constraints)[0];\n acc[_path] = {\n type: key,\n message: error.constraints[key],\n };\n\n const _e = acc[_path];\n if (validateAllFieldCriteria && _e) {\n Object.assign(_e, { types: error.constraints });\n }\n }\n\n if (error.children && error.children.length) {\n parseErrorSchema(error.children, validateAllFieldCriteria, acc, _path);\n }\n\n return acc;\n }, parsedErrors);\n}\n\n/**\n * Creates a resolver for react-hook-form using class-validator schema validation\n * @param {ClassConstructor<Schema>} schema - The class-validator schema to validate against\n * @param {Object} schemaOptions - Additional schema validation options\n * @param {Object} resolverOptions - Additional resolver configuration\n * @param {string} [resolverOptions.mode='async'] - Validation mode\n * @returns {Resolver<Schema>} A resolver function compatible with react-hook-form\n * @example\n * class Schema {\n * @Matches(/^\\w+$/)\n * @Length(3, 30)\n * username: string;\n * age: number\n * }\n *\n * useForm({\n * resolver: classValidatorResolver(Schema)\n * });\n */\nexport function classValidatorResolver<Schema extends Record<string, any>>(\n schema: ClassConstructor<Schema>,\n schemaOptions: {\n validator?: ValidatorOptions;\n transformer?: ClassTransformOptions;\n } = {},\n resolverOptions: { mode?: 'async' | 'sync'; raw?: boolean } = {},\n): Resolver<Schema> {\n return async (values, _, options) => {\n const { transformer, validator } = schemaOptions;\n const data = plainToClass(schema, values, transformer);\n\n const rawErrors = await (resolverOptions.mode === 'sync'\n ? validateSync\n : validate)(data, validator);\n\n if (rawErrors.length) {\n return {\n values: {},\n errors: toNestErrors(\n parseErrorSchema(\n rawErrors,\n !options.shouldUseNativeValidation &&\n options.criteriaMode === 'all',\n ),\n options,\n ),\n };\n }\n\n options.shouldUseNativeValidation && validateFieldsNatively({}, options);\n\n return {\n values: resolverOptions.raw ? Object.assign({}, values) : data,\n errors: {},\n };\n };\n}\n"],"names":["parseErrorSchema","errors","validateAllFieldCriteria","parsedErrors","path","reduce","acc","error","_path","property","constraints","key","Object","keys","type","message","_e","assign","types","children","length","schema","schemaOptions","resolverOptions","values","_","options","validator","data","plainToClass","transformer","Promise","resolve","mode","validateSync","validate","then","rawErrors","toNestErrors","shouldUseNativeValidation","criteriaMode","validateFieldsNatively","raw","e","reject"],"mappings":"0cAcA,SAASA,EACPC,EACAC,EACAC,EACAC,GAEA,YAHA,IAAAD,IAAAA,EAA4B,CAAE,YAC9BC,IAAAA,EAAO,IAEAH,EAAOI,OAAO,SAACC,EAAKC,GACzB,IAAMC,EAAQJ,EAAUA,EAAI,IAAIG,EAAME,SAAaF,EAAME,SAEzD,GAAIF,EAAMG,YAAa,CACrB,IAAMC,EAAMC,OAAOC,KAAKN,EAAMG,aAAa,GAC3CJ,EAAIE,GAAS,CACXM,KAAMH,EACNI,QAASR,EAAMG,YAAYC,IAG7B,IAAMK,EAAKV,EAAIE,GACXN,GAA4Bc,GAC9BJ,OAAOK,OAAOD,EAAI,CAAEE,MAAOX,EAAMG,aAErC,CAMA,OAJIH,EAAMY,UAAYZ,EAAMY,SAASC,QACnCpB,EAAiBO,EAAMY,SAAUjB,EAA0BI,EAAKE,GAG3DF,CACT,EAAGH,EACL,0BAqBM,SACJkB,EACAC,EAIAC,GAEA,gBANAD,IAAAA,EAGI,CAAE,QACN,IAAAC,IAAAA,EAA8D,CAAE,GAEhE,SAAcC,EAAQC,EAAGC,OACvB,IAAqBC,EAAcL,EAAdK,UACfC,EAAOC,EAAYA,aAACR,EAAQG,EADCF,EAA3BQ,aAC+C,OAAAC,QAAAC,SAEL,SAAzBT,EAAgBU,KACrCC,eACAC,EAAAA,UAAUP,EAAMD,IAAUS,KAFxBC,SAAAA,GAIN,OAAIA,EAAUjB,OACL,CACLI,OAAQ,CAAA,EACRvB,OAAQqC,eACNtC,EACEqC,GACCX,EAAQa,2BACkB,QAAzBb,EAAQc,cAEZd,KAKNA,EAAQa,2BAA6BE,EAAsBA,uBAAC,CAAE,EAAEf,GAEzD,CACLF,OAAQD,EAAgBmB,IAAM9B,OAAOK,OAAO,CAAE,EAAEO,GAAUI,EAC1D3B,OAAQ,CAAA,GACR,EACJ,CAAC,MAAA0C,GAAAZ,OAAAA,QAAAa,OAAAD,EACH,CAAA,CAAA"}

View file

@ -0,0 +1 @@
export * from './class-validator';

View file

@ -0,0 +1,19 @@
{
"name": "@hookform/resolvers/class-validator",
"amdName": "hookformResolversClassValidator",
"version": "1.0.0",
"private": true,
"description": "React Hook Form validation resolver: class-validator",
"main": "dist/class-validator.js",
"module": "dist/class-validator.module.js",
"umd:main": "dist/class-validator.umd.js",
"source": "src/index.ts",
"types": "dist/index.d.ts",
"license": "MIT",
"peerDependencies": {
"react-hook-form": ">=6.6.0",
"@hookform/resolvers": ">=2.0.0",
"class-transformer": "^0.4.0",
"class-validator": "^0.12.0"
}
}

View file

@ -0,0 +1,79 @@
import { render, screen } from '@testing-library/react';
import user from '@testing-library/user-event';
import { IsNotEmpty } from 'class-validator';
import React from 'react';
import { SubmitHandler, useForm } from 'react-hook-form';
import { classValidatorResolver } from '..';
class Schema {
@IsNotEmpty()
username: string;
@IsNotEmpty()
password: string;
}
interface Props {
onSubmit: SubmitHandler<Schema>;
}
function TestComponent({ onSubmit }: Props) {
const { register, handleSubmit } = useForm<Schema>({
resolver: classValidatorResolver(Schema),
shouldUseNativeValidation: true,
});
return (
<form onSubmit={handleSubmit(onSubmit)}>
<input {...register('username')} placeholder="username" />
<input {...register('password')} placeholder="password" />
<button type="submit">submit</button>
</form>
);
}
test("form's native validation with Class Validator", async () => {
const handleSubmit = vi.fn();
render(<TestComponent onSubmit={handleSubmit} />);
// username
let usernameField = screen.getByPlaceholderText(
/username/i,
) as HTMLInputElement;
expect(usernameField.validity.valid).toBe(true);
expect(usernameField.validationMessage).toBe('');
// password
let passwordField = screen.getByPlaceholderText(
/password/i,
) as HTMLInputElement;
expect(passwordField.validity.valid).toBe(true);
expect(passwordField.validationMessage).toBe('');
await user.click(screen.getByText(/submit/i));
// username
usernameField = screen.getByPlaceholderText(/username/i) as HTMLInputElement;
expect(usernameField.validity.valid).toBe(false);
expect(usernameField.validationMessage).toBe('username should not be empty');
// password
passwordField = screen.getByPlaceholderText(/password/i) as HTMLInputElement;
expect(passwordField.validity.valid).toBe(false);
expect(passwordField.validationMessage).toBe('password should not be empty');
await user.type(screen.getByPlaceholderText(/username/i), 'joe');
await user.type(screen.getByPlaceholderText(/password/i), 'password');
// username
usernameField = screen.getByPlaceholderText(/username/i) as HTMLInputElement;
expect(usernameField.validity.valid).toBe(true);
expect(usernameField.validationMessage).toBe('');
// password
passwordField = screen.getByPlaceholderText(/password/i) as HTMLInputElement;
expect(passwordField.validity.valid).toBe(true);
expect(passwordField.validationMessage).toBe('');
});

View file

@ -0,0 +1,53 @@
import { render, screen } from '@testing-library/react';
import user from '@testing-library/user-event';
import { IsNotEmpty } from 'class-validator';
import React from 'react';
import { SubmitHandler, useForm } from 'react-hook-form';
import { classValidatorResolver } from '..';
class Schema {
@IsNotEmpty()
username: string;
@IsNotEmpty()
password: string;
}
interface Props {
onSubmit: SubmitHandler<Schema>;
}
function TestComponent({ onSubmit }: Props) {
const {
register,
formState: { errors },
handleSubmit,
} = useForm<Schema>({
resolver: classValidatorResolver(Schema),
});
return (
<form onSubmit={handleSubmit(onSubmit)}>
<input {...register('username')} />
{errors.username && <span role="alert">{errors.username.message}</span>}
<input {...register('password')} />
{errors.password && <span role="alert">{errors.password.message}</span>}
<button type="submit">submit</button>
</form>
);
}
test("form's validation with Class Validator and TypeScript's integration", async () => {
const handleSubmit = vi.fn();
render(<TestComponent onSubmit={handleSubmit} />);
expect(screen.queryAllByRole('alert')).toHaveLength(0);
await user.click(screen.getByText(/submit/i));
expect(screen.getByText(/username should not be empty/i)).toBeInTheDocument();
expect(screen.getByText(/password should not be empty/i)).toBeInTheDocument();
expect(handleSubmit).not.toHaveBeenCalled();
});

View file

@ -0,0 +1,88 @@
import 'reflect-metadata';
import { Type } from 'class-transformer';
import {
IsEmail,
IsNotEmpty,
Length,
Matches,
Max,
Min,
ValidateNested,
} from 'class-validator';
import { Field, InternalFieldName } from 'react-hook-form';
class Like {
@IsNotEmpty()
id: number;
@Length(4)
name: string;
}
export class Schema {
@Matches(/^\w+$/)
@Length(3, 30)
username: string;
@Matches(/^[a-zA-Z0-9]{3,30}/)
password: string;
@Min(1900)
@Max(2013)
birthYear: number;
@IsEmail()
email: string;
accessToken: string;
tags: string[];
enabled: boolean;
@ValidateNested({ each: true })
@Type(() => Like)
like: Like[];
}
export const validData: Schema = {
username: 'Doe',
password: 'Password123',
birthYear: 2000,
email: 'john@doe.com',
tags: ['tag1', 'tag2'],
enabled: true,
accessToken: 'accessToken',
like: [
{
id: 1,
name: 'name',
},
],
};
export const invalidData = {
password: '___',
email: '',
birthYear: 'birthYear',
like: [{ id: 'z' }],
} as any as Schema;
export const fields: Record<InternalFieldName, Field['_f']> = {
username: {
ref: { name: 'username' },
name: 'username',
},
password: {
ref: { name: 'password' },
name: 'password',
},
email: {
ref: { name: 'email' },
name: 'email',
},
birthday: {
ref: { name: 'birthday' },
name: 'birthday',
},
};

View file

@ -0,0 +1,242 @@
// Vitest Snapshot v1, https://vitest.dev/guide/snapshot.html
exports[`classValidatorResolver > should return a single error from classValidatorResolver when validation fails 1`] = `
{
"errors": {
"birthYear": {
"message": "birthYear must not be greater than 2013",
"ref": undefined,
"type": "max",
},
"email": {
"message": "email must be an email",
"ref": {
"name": "email",
},
"type": "isEmail",
},
"like": [
{
"name": {
"message": "name must be longer than or equal to 4 characters",
"ref": undefined,
"type": "isLength",
},
},
],
"password": {
"message": "password must match /^[a-zA-Z0-9]{3,30}/ regular expression",
"ref": {
"name": "password",
},
"type": "matches",
},
"username": {
"message": "username must be longer than or equal to 3 characters",
"ref": {
"name": "username",
},
"type": "isLength",
},
},
"values": {},
}
`;
exports[`classValidatorResolver > should return a single error from classValidatorResolver with \`mode: sync\` when validation fails 1`] = `
{
"errors": {
"birthYear": {
"message": "birthYear must not be greater than 2013",
"ref": undefined,
"type": "max",
},
"email": {
"message": "email must be an email",
"ref": {
"name": "email",
},
"type": "isEmail",
},
"like": [
{
"name": {
"message": "name must be longer than or equal to 4 characters",
"ref": undefined,
"type": "isLength",
},
},
],
"password": {
"message": "password must match /^[a-zA-Z0-9]{3,30}/ regular expression",
"ref": {
"name": "password",
},
"type": "matches",
},
"username": {
"message": "username must be longer than or equal to 3 characters",
"ref": {
"name": "username",
},
"type": "isLength",
},
},
"values": {},
}
`;
exports[`classValidatorResolver > should return all the errors from classValidatorResolver when validation fails with \`validateAllFieldCriteria\` set to true 1`] = `
{
"errors": {
"birthYear": {
"message": "birthYear must not be greater than 2013",
"ref": undefined,
"type": "max",
"types": {
"max": "birthYear must not be greater than 2013",
"min": "birthYear must not be less than 1900",
},
},
"email": {
"message": "email must be an email",
"ref": {
"name": "email",
},
"type": "isEmail",
"types": {
"isEmail": "email must be an email",
},
},
"like": [
{
"name": {
"message": "name must be longer than or equal to 4 characters",
"ref": undefined,
"type": "isLength",
"types": {
"isLength": "name must be longer than or equal to 4 characters",
},
},
},
],
"password": {
"message": "password must match /^[a-zA-Z0-9]{3,30}/ regular expression",
"ref": {
"name": "password",
},
"type": "matches",
"types": {
"matches": "password must match /^[a-zA-Z0-9]{3,30}/ regular expression",
},
},
"username": {
"message": "username must be longer than or equal to 3 characters",
"ref": {
"name": "username",
},
"type": "isLength",
"types": {
"isLength": "username must be longer than or equal to 3 characters",
"matches": "username must match /^\\w+$/ regular expression",
},
},
},
"values": {},
}
`;
exports[`classValidatorResolver > should return all the errors from classValidatorResolver when validation fails with \`validateAllFieldCriteria\` set to true and \`mode: sync\` 1`] = `
{
"errors": {
"birthYear": {
"message": "birthYear must not be greater than 2013",
"ref": undefined,
"type": "max",
"types": {
"max": "birthYear must not be greater than 2013",
"min": "birthYear must not be less than 1900",
},
},
"email": {
"message": "email must be an email",
"ref": {
"name": "email",
},
"type": "isEmail",
"types": {
"isEmail": "email must be an email",
},
},
"like": [
{
"name": {
"message": "name must be longer than or equal to 4 characters",
"ref": undefined,
"type": "isLength",
"types": {
"isLength": "name must be longer than or equal to 4 characters",
},
},
},
],
"password": {
"message": "password must match /^[a-zA-Z0-9]{3,30}/ regular expression",
"ref": {
"name": "password",
},
"type": "matches",
"types": {
"matches": "password must match /^[a-zA-Z0-9]{3,30}/ regular expression",
},
},
"username": {
"message": "username must be longer than or equal to 3 characters",
"ref": {
"name": "username",
},
"type": "isLength",
"types": {
"isLength": "username must be longer than or equal to 3 characters",
"matches": "username must match /^\\w+$/ regular expression",
},
},
},
"values": {},
}
`;
exports[`validate data with transformer option 1`] = `
{
"errors": {
"random": {
"message": "All fields must be defined.",
"ref": undefined,
"type": "isDefined",
"types": {
"isDefined": "All fields must be defined.",
"isNumber": "Must be a number",
"max": "Cannot be greater than 255",
"min": "Cannot be lower than 0",
},
},
},
"values": {},
}
`;
exports[`validate data with validator option 1`] = `
{
"errors": {
"random": {
"message": "All fields must be defined.",
"ref": undefined,
"type": "isDefined",
"types": {
"isDefined": "All fields must be defined.",
},
},
},
"values": {},
}
`;

View file

@ -0,0 +1,199 @@
import { Expose, Type } from 'class-transformer';
import * as classValidator from 'class-validator';
import { IsDefined, IsNumber, Max, Min } from 'class-validator';
/* eslint-disable no-console, @typescript-eslint/ban-ts-comment */
import { classValidatorResolver } from '..';
import { Schema, fields, invalidData, validData } from './__fixtures__/data';
const shouldUseNativeValidation = false;
describe('classValidatorResolver', () => {
it('should return values from classValidatorResolver when validation pass', async () => {
const schemaSpy = vi.spyOn(classValidator, 'validate');
const schemaSyncSpy = vi.spyOn(classValidator, 'validateSync');
const result = await classValidatorResolver(Schema)(validData, undefined, {
fields,
shouldUseNativeValidation,
});
expect(schemaSpy).toHaveBeenCalledTimes(1);
expect(schemaSyncSpy).not.toHaveBeenCalled();
expect(result).toEqual({ errors: {}, values: validData });
expect(result.values).toBeInstanceOf(Schema);
});
it('should return values as a raw object from classValidatorResolver when `rawValues` set to true', async () => {
const result = await classValidatorResolver(Schema, undefined, {
raw: true,
})(validData, undefined, {
fields,
shouldUseNativeValidation,
});
expect(result).toEqual({ errors: {}, values: validData });
expect(result.values).not.toBeInstanceOf(Schema);
});
it('should return values from classValidatorResolver with `mode: sync` when validation pass', async () => {
const validateSyncSpy = vi.spyOn(classValidator, 'validateSync');
const validateSpy = vi.spyOn(classValidator, 'validate');
const result = await classValidatorResolver(Schema, undefined, {
mode: 'sync',
})(validData, undefined, { fields, shouldUseNativeValidation });
expect(validateSyncSpy).toHaveBeenCalledTimes(1);
expect(validateSpy).not.toHaveBeenCalled();
expect(result).toEqual({ errors: {}, values: validData });
expect(result.values).toBeInstanceOf(Schema);
});
it('should return a single error from classValidatorResolver when validation fails', async () => {
const result = await classValidatorResolver(Schema)(
invalidData,
undefined,
{
fields,
shouldUseNativeValidation,
},
);
expect(result).toMatchSnapshot();
});
it('should return a single error from classValidatorResolver with `mode: sync` when validation fails', async () => {
const validateSyncSpy = vi.spyOn(classValidator, 'validateSync');
const validateSpy = vi.spyOn(classValidator, 'validate');
const result = await classValidatorResolver(Schema, undefined, {
mode: 'sync',
})(invalidData, undefined, { fields, shouldUseNativeValidation });
expect(validateSyncSpy).toHaveBeenCalledTimes(1);
expect(validateSpy).not.toHaveBeenCalled();
expect(result).toMatchSnapshot();
});
it('should return all the errors from classValidatorResolver when validation fails with `validateAllFieldCriteria` set to true', async () => {
const result = await classValidatorResolver(Schema)(
invalidData,
undefined,
{
fields,
criteriaMode: 'all',
shouldUseNativeValidation,
},
);
expect(result).toMatchSnapshot();
});
it('should return all the errors from classValidatorResolver when validation fails with `validateAllFieldCriteria` set to true and `mode: sync`', async () => {
const result = await classValidatorResolver(Schema, undefined, {
mode: 'sync',
})(invalidData, undefined, {
fields,
criteriaMode: 'all',
shouldUseNativeValidation,
});
expect(result).toMatchSnapshot();
});
});
it('validate data with transformer option', async () => {
class SchemaTest {
@Expose({ groups: ['find', 'create', 'update'] })
@Type(() => Number)
@IsDefined({
message: `All fields must be defined.`,
groups: ['publish'],
})
@IsNumber({}, { message: `Must be a number`, always: true })
@Min(0, { message: `Cannot be lower than 0`, always: true })
@Max(255, { message: `Cannot be greater than 255`, always: true })
random: number;
}
const result = await classValidatorResolver(
SchemaTest,
{ transformer: { groups: ['update'] } },
{
mode: 'sync',
},
)(
// @ts-expect-error - Just for testing purposes
invalidData,
undefined,
{
fields,
criteriaMode: 'all',
shouldUseNativeValidation,
},
);
expect(result).toMatchSnapshot();
});
it('validate data with validator option', async () => {
class SchemaTest {
@Expose({ groups: ['find', 'create', 'update'] })
@Type(() => Number)
@IsDefined({
message: `All fields must be defined.`,
groups: ['publish'],
})
@IsNumber({}, { message: `Must be a number`, always: true })
@Min(0, { message: `Cannot be lower than 0`, always: true })
@Max(255, { message: `Cannot be greater than 255`, always: true })
random: number;
}
const result = await classValidatorResolver(
SchemaTest,
{ validator: { stopAtFirstError: true } },
{
mode: 'sync',
},
)(
// @ts-expect-error - Just for testing purposes
invalidData,
undefined,
{
fields,
criteriaMode: 'all',
shouldUseNativeValidation,
},
);
expect(result).toMatchSnapshot();
});
it('should return from classValidatorResolver with `excludeExtraneousValues` set to true', async () => {
class SchemaTest {
@Expose()
@IsNumber({}, { message: `Must be a number`, always: true })
random: number;
}
const result = await classValidatorResolver(SchemaTest, {
transformer: {
excludeExtraneousValues: true,
},
})(
{
random: 10,
// @ts-expect-error - Just for testing purposes
extraneousField: true,
},
undefined,
{
fields,
shouldUseNativeValidation,
},
);
expect(result).toEqual({ errors: {}, values: { random: 10 } });
expect(result.values).toBeInstanceOf(SchemaTest);
});

View file

@ -0,0 +1,101 @@
import { toNestErrors, validateFieldsNatively } from '@hookform/resolvers';
import {
ClassConstructor,
ClassTransformOptions,
plainToClass,
} from 'class-transformer';
import {
ValidationError,
ValidatorOptions,
validate,
validateSync,
} from 'class-validator';
import { FieldErrors, Resolver } from 'react-hook-form';
function parseErrorSchema(
errors: ValidationError[],
validateAllFieldCriteria: boolean,
parsedErrors: FieldErrors = {},
path = '',
) {
return errors.reduce((acc, error) => {
const _path = path ? `${path}.${error.property}` : error.property;
if (error.constraints) {
const key = Object.keys(error.constraints)[0];
acc[_path] = {
type: key,
message: error.constraints[key],
};
const _e = acc[_path];
if (validateAllFieldCriteria && _e) {
Object.assign(_e, { types: error.constraints });
}
}
if (error.children && error.children.length) {
parseErrorSchema(error.children, validateAllFieldCriteria, acc, _path);
}
return acc;
}, parsedErrors);
}
/**
* Creates a resolver for react-hook-form using class-validator schema validation
* @param {ClassConstructor<Schema>} schema - The class-validator schema to validate against
* @param {Object} schemaOptions - Additional schema validation options
* @param {Object} resolverOptions - Additional resolver configuration
* @param {string} [resolverOptions.mode='async'] - Validation mode
* @returns {Resolver<Schema>} A resolver function compatible with react-hook-form
* @example
* class Schema {
* @Matches(/^\w+$/)
* @Length(3, 30)
* username: string;
* age: number
* }
*
* useForm({
* resolver: classValidatorResolver(Schema)
* });
*/
export function classValidatorResolver<Schema extends Record<string, any>>(
schema: ClassConstructor<Schema>,
schemaOptions: {
validator?: ValidatorOptions;
transformer?: ClassTransformOptions;
} = {},
resolverOptions: { mode?: 'async' | 'sync'; raw?: boolean } = {},
): Resolver<Schema> {
return async (values, _, options) => {
const { transformer, validator } = schemaOptions;
const data = plainToClass(schema, values, transformer);
const rawErrors = await (resolverOptions.mode === 'sync'
? validateSync
: validate)(data, validator);
if (rawErrors.length) {
return {
values: {},
errors: toNestErrors(
parseErrorSchema(
rawErrors,
!options.shouldUseNativeValidation &&
options.criteriaMode === 'all',
),
options,
),
};
}
options.shouldUseNativeValidation && validateFieldsNatively({}, options);
return {
values: resolverOptions.raw ? Object.assign({}, values) : data,
errors: {},
};
};
}

View file

@ -0,0 +1 @@
export * from './class-validator';

View file

@ -0,0 +1,17 @@
import FunctionType from 'computed-types/lib/schema/FunctionType';
import type { FieldValues, Resolver } from 'react-hook-form';
/**
* Creates a resolver for react-hook-form using computed-types schema validation
* @param {Schema} schema - The computed-types schema to validate against
* @returns {Resolver<Type<typeof schema>>} A resolver function compatible with react-hook-form
* @example
* const schema = Schema({
* name: string,
* age: number
* });
*
* useForm({
* resolver: computedTypesResolver(schema)
* });
*/
export declare function computedTypesResolver<Input extends FieldValues, Context, Output>(schema: FunctionType<Output, [Input]>): Resolver<Input, Context, Output>;

View file

@ -0,0 +1,2 @@
var r=require("@hookform/resolvers");exports.computedTypesResolver=function(e){return function(t,o,n){try{return Promise.resolve(function(o,s){try{var u=Promise.resolve(e(t)).then(function(e){return n.shouldUseNativeValidation&&r.validateFieldsNatively({},n),{errors:{},values:e}})}catch(r){return s(r)}return u&&u.then?u.then(void 0,s):u}(0,function(e){if(function(r){return null!=r.errors}(e))return{values:{},errors:r.toNestErrors((t=e,(t.errors||[]).reduce(function(r,e){return r[e.path.join(".")]={type:e.error.name,message:e.error.message},r},{})),n)};var t;throw e}))}catch(r){return Promise.reject(r)}}};
//# sourceMappingURL=computed-types.js.map

View file

@ -0,0 +1 @@
{"version":3,"file":"computed-types.js","sources":["../src/computed-types.ts"],"sourcesContent":["import { toNestErrors, validateFieldsNatively } from '@hookform/resolvers';\nimport { ValidationError } from 'computed-types';\nimport FunctionType from 'computed-types/lib/schema/FunctionType';\nimport type { FieldErrors, FieldValues, Resolver } from 'react-hook-form';\n\nconst isValidationError = (error: any): error is ValidationError =>\n error.errors != null;\n\nfunction parseErrorSchema(computedTypesError: ValidationError) {\n const parsedErrors: FieldErrors = {};\n return (computedTypesError.errors || []).reduce((acc, error) => {\n acc[error.path.join('.')] = {\n type: error.error.name,\n message: error.error.message,\n };\n\n return acc;\n }, parsedErrors);\n}\n\n/**\n * Creates a resolver for react-hook-form using computed-types schema validation\n * @param {Schema} schema - The computed-types schema to validate against\n * @returns {Resolver<Type<typeof schema>>} A resolver function compatible with react-hook-form\n * @example\n * const schema = Schema({\n * name: string,\n * age: number\n * });\n *\n * useForm({\n * resolver: computedTypesResolver(schema)\n * });\n */\nexport function computedTypesResolver<\n Input extends FieldValues,\n Context,\n Output,\n>(schema: FunctionType<Output, [Input]>): Resolver<Input, Context, Output> {\n return async (values, _, options) => {\n try {\n const data = await schema(values);\n\n options.shouldUseNativeValidation && validateFieldsNatively({}, options);\n\n return {\n errors: {},\n values: data,\n };\n } catch (error: any) {\n if (isValidationError(error)) {\n return {\n values: {},\n errors: toNestErrors(parseErrorSchema(error), options),\n };\n }\n\n throw error;\n }\n };\n}\n"],"names":["schema","values","_","options","Promise","resolve","then","data","shouldUseNativeValidation","validateFieldsNatively","errors","_catch","error","isValidationError","toNestErrors","computedTypesError","reduce","acc","path","join","type","name","message","e","reject"],"mappings":"mEAkCM,SAIJA,GACA,OAAcC,SAAAA,EAAQC,EAAGC,GAAW,IAAA,OAAAC,QAAAC,gCAC9BD,QAAAC,QACiBL,EAAOC,IAAOK,KAAA,SAA3BC,GAIN,OAFAJ,EAAQK,2BAA6BC,EAAAA,uBAAuB,CAAA,EAAIN,GAEzD,CACLO,OAAQ,CAAA,EACRT,OAAQM,EACR,4DAT8BI,CAAA,EAUjC,SAAQC,GACP,GA7CoB,SAACA,GACzB,OAAgB,MAAhBA,EAAMF,MAAc,CA4CZG,CAAkBD,GACpB,MAAO,CACLX,OAAQ,CAAE,EACVS,OAAQI,gBA7CQC,EA6CsBH,GA3CtCG,EAAmBL,QAAU,IAAIM,OAAO,SAACC,EAAKL,GAMpD,OALAK,EAAIL,EAAMM,KAAKC,KAAK,MAAQ,CAC1BC,KAAMR,EAAMA,MAAMS,KAClBC,QAASV,EAAMA,MAAMU,SAGhBL,CACT,EARkC,CAAE,IA4CkBd,IA7CxD,IAA0BY,EAiDpB,MAAMH,CACR,GACF,CAAC,MAAAW,GAAAnB,OAAAA,QAAAoB,OAAAD,EACH,CAAA,CAAA"}

View file

@ -0,0 +1,2 @@
import{validateFieldsNatively as r,toNestErrors as e}from"@hookform/resolvers";function t(t){return function(n,o,u){try{return Promise.resolve(function(e,o){try{var s=Promise.resolve(t(n)).then(function(e){return u.shouldUseNativeValidation&&r({},u),{errors:{},values:e}})}catch(r){return o(r)}return s&&s.then?s.then(void 0,o):s}(0,function(r){if(function(r){return null!=r.errors}(r))return{values:{},errors:e((t=r,(t.errors||[]).reduce(function(r,e){return r[e.path.join(".")]={type:e.error.name,message:e.error.message},r},{})),u)};var t;throw r}))}catch(r){return Promise.reject(r)}}}export{t as computedTypesResolver};
//# sourceMappingURL=computed-types.module.js.map

View file

@ -0,0 +1,2 @@
import{validateFieldsNatively as r,toNestErrors as e}from"@hookform/resolvers";function o(o){return async(s,t,a)=>{try{const e=await o(s);return a.shouldUseNativeValidation&&r({},a),{errors:{},values:e}}catch(r){if((r=>null!=r.errors)(r))return{values:{},errors:e((n=r,(n.errors||[]).reduce((r,e)=>(r[e.path.join(".")]={type:e.error.name,message:e.error.message},r),{})),a)};throw r}var n}}export{o as computedTypesResolver};
//# sourceMappingURL=computed-types.modern.mjs.map

View file

@ -0,0 +1 @@
{"version":3,"file":"computed-types.modern.mjs","sources":["../src/computed-types.ts"],"sourcesContent":["import { toNestErrors, validateFieldsNatively } from '@hookform/resolvers';\nimport { ValidationError } from 'computed-types';\nimport FunctionType from 'computed-types/lib/schema/FunctionType';\nimport type { FieldErrors, FieldValues, Resolver } from 'react-hook-form';\n\nconst isValidationError = (error: any): error is ValidationError =>\n error.errors != null;\n\nfunction parseErrorSchema(computedTypesError: ValidationError) {\n const parsedErrors: FieldErrors = {};\n return (computedTypesError.errors || []).reduce((acc, error) => {\n acc[error.path.join('.')] = {\n type: error.error.name,\n message: error.error.message,\n };\n\n return acc;\n }, parsedErrors);\n}\n\n/**\n * Creates a resolver for react-hook-form using computed-types schema validation\n * @param {Schema} schema - The computed-types schema to validate against\n * @returns {Resolver<Type<typeof schema>>} A resolver function compatible with react-hook-form\n * @example\n * const schema = Schema({\n * name: string,\n * age: number\n * });\n *\n * useForm({\n * resolver: computedTypesResolver(schema)\n * });\n */\nexport function computedTypesResolver<\n Input extends FieldValues,\n Context,\n Output,\n>(schema: FunctionType<Output, [Input]>): Resolver<Input, Context, Output> {\n return async (values, _, options) => {\n try {\n const data = await schema(values);\n\n options.shouldUseNativeValidation && validateFieldsNatively({}, options);\n\n return {\n errors: {},\n values: data,\n };\n } catch (error: any) {\n if (isValidationError(error)) {\n return {\n values: {},\n errors: toNestErrors(parseErrorSchema(error), options),\n };\n }\n\n throw error;\n }\n };\n}\n"],"names":["computedTypesResolver","schema","values","_","options","data","shouldUseNativeValidation","validateFieldsNatively","errors","error","isValidationError","toNestErrors","computedTypesError","reduce","acc","path","join","type","name","message"],"mappings":"+EAkCgB,SAAAA,EAIdC,GACA,aAAcC,EAAQC,EAAGC,KACvB,IACE,MAAMC,QAAaJ,EAAOC,GAI1B,OAFAE,EAAQE,2BAA6BC,EAAuB,CAAA,EAAIH,GAEzD,CACLI,OAAQ,CAAE,EACVN,OAAQG,EAEZ,CAAE,MAAOI,GACP,GA7CqBA,IACT,MAAhBA,EAAMD,OA4CEE,CAAkBD,GACpB,MAAO,CACLP,OAAQ,CAAE,EACVM,OAAQG,GA7CQC,EA6CsBH,GA3CtCG,EAAmBJ,QAAU,IAAIK,OAAO,CAACC,EAAKL,KACpDK,EAAIL,EAAMM,KAAKC,KAAK,MAAQ,CAC1BC,KAAMR,EAAMA,MAAMS,KAClBC,QAASV,EAAMA,MAAMU,SAGhBL,GAPyB,KA4CoBV,IAIlD,MAAMK,CACR,CAlDJ,IAA0BG,CAkDtB,CAEJ"}

View file

@ -0,0 +1,2 @@
import{validateFieldsNatively as r,toNestErrors as e}from"@hookform/resolvers";function t(t){return function(n,o,u){try{return Promise.resolve(function(e,o){try{var s=Promise.resolve(t(n)).then(function(e){return u.shouldUseNativeValidation&&r({},u),{errors:{},values:e}})}catch(r){return o(r)}return s&&s.then?s.then(void 0,o):s}(0,function(r){if(function(r){return null!=r.errors}(r))return{values:{},errors:e((t=r,(t.errors||[]).reduce(function(r,e){return r[e.path.join(".")]={type:e.error.name,message:e.error.message},r},{})),u)};var t;throw r}))}catch(r){return Promise.reject(r)}}}export{t as computedTypesResolver};
//# sourceMappingURL=computed-types.module.js.map

View file

@ -0,0 +1 @@
{"version":3,"file":"computed-types.module.js","sources":["../src/computed-types.ts"],"sourcesContent":["import { toNestErrors, validateFieldsNatively } from '@hookform/resolvers';\nimport { ValidationError } from 'computed-types';\nimport FunctionType from 'computed-types/lib/schema/FunctionType';\nimport type { FieldErrors, FieldValues, Resolver } from 'react-hook-form';\n\nconst isValidationError = (error: any): error is ValidationError =>\n error.errors != null;\n\nfunction parseErrorSchema(computedTypesError: ValidationError) {\n const parsedErrors: FieldErrors = {};\n return (computedTypesError.errors || []).reduce((acc, error) => {\n acc[error.path.join('.')] = {\n type: error.error.name,\n message: error.error.message,\n };\n\n return acc;\n }, parsedErrors);\n}\n\n/**\n * Creates a resolver for react-hook-form using computed-types schema validation\n * @param {Schema} schema - The computed-types schema to validate against\n * @returns {Resolver<Type<typeof schema>>} A resolver function compatible with react-hook-form\n * @example\n * const schema = Schema({\n * name: string,\n * age: number\n * });\n *\n * useForm({\n * resolver: computedTypesResolver(schema)\n * });\n */\nexport function computedTypesResolver<\n Input extends FieldValues,\n Context,\n Output,\n>(schema: FunctionType<Output, [Input]>): Resolver<Input, Context, Output> {\n return async (values, _, options) => {\n try {\n const data = await schema(values);\n\n options.shouldUseNativeValidation && validateFieldsNatively({}, options);\n\n return {\n errors: {},\n values: data,\n };\n } catch (error: any) {\n if (isValidationError(error)) {\n return {\n values: {},\n errors: toNestErrors(parseErrorSchema(error), options),\n };\n }\n\n throw error;\n }\n };\n}\n"],"names":["computedTypesResolver","schema","values","_","options","Promise","resolve","then","data","shouldUseNativeValidation","validateFieldsNatively","errors","_catch","error","isValidationError","toNestErrors","computedTypesError","reduce","acc","path","join","type","name","message","e","reject"],"mappings":"+EAkCM,SAAUA,EAIdC,GACA,OAAcC,SAAAA,EAAQC,EAAGC,GAAW,IAAA,OAAAC,QAAAC,gCAC9BD,QAAAC,QACiBL,EAAOC,IAAOK,KAAA,SAA3BC,GAIN,OAFAJ,EAAQK,2BAA6BC,EAAuB,CAAA,EAAIN,GAEzD,CACLO,OAAQ,CAAA,EACRT,OAAQM,EACR,4DAT8BI,CAAA,EAUjC,SAAQC,GACP,GA7CoB,SAACA,GACzB,OAAgB,MAAhBA,EAAMF,MAAc,CA4CZG,CAAkBD,GACpB,MAAO,CACLX,OAAQ,CAAE,EACVS,OAAQI,GA7CQC,EA6CsBH,GA3CtCG,EAAmBL,QAAU,IAAIM,OAAO,SAACC,EAAKL,GAMpD,OALAK,EAAIL,EAAMM,KAAKC,KAAK,MAAQ,CAC1BC,KAAMR,EAAMA,MAAMS,KAClBC,QAASV,EAAMA,MAAMU,SAGhBL,CACT,EARkC,CAAE,IA4CkBd,IA7CxD,IAA0BY,EAiDpB,MAAMH,CACR,GACF,CAAC,MAAAW,GAAAnB,OAAAA,QAAAoB,OAAAD,EACH,CAAA,CAAA"}

View file

@ -0,0 +1,2 @@
!function(e,r){"object"==typeof exports&&"undefined"!=typeof module?r(exports,require("@hookform/resolvers")):"function"==typeof define&&define.amd?define(["exports","@hookform/resolvers"],r):r((e||self).hookformResolversComputedTypes={},e.hookformResolvers)}(this,function(e,r){e.computedTypesResolver=function(e){return function(o,t,n){try{return Promise.resolve(function(t,s){try{var i=Promise.resolve(e(o)).then(function(e){return n.shouldUseNativeValidation&&r.validateFieldsNatively({},n),{errors:{},values:e}})}catch(e){return s(e)}return i&&i.then?i.then(void 0,s):i}(0,function(e){if(function(e){return null!=e.errors}(e))return{values:{},errors:r.toNestErrors((o=e,(o.errors||[]).reduce(function(e,r){return e[r.path.join(".")]={type:r.error.name,message:r.error.message},e},{})),n)};var o;throw e}))}catch(e){return Promise.reject(e)}}}});
//# sourceMappingURL=computed-types.umd.js.map

View file

@ -0,0 +1 @@
{"version":3,"file":"computed-types.umd.js","sources":["../src/computed-types.ts"],"sourcesContent":["import { toNestErrors, validateFieldsNatively } from '@hookform/resolvers';\nimport { ValidationError } from 'computed-types';\nimport FunctionType from 'computed-types/lib/schema/FunctionType';\nimport type { FieldErrors, FieldValues, Resolver } from 'react-hook-form';\n\nconst isValidationError = (error: any): error is ValidationError =>\n error.errors != null;\n\nfunction parseErrorSchema(computedTypesError: ValidationError) {\n const parsedErrors: FieldErrors = {};\n return (computedTypesError.errors || []).reduce((acc, error) => {\n acc[error.path.join('.')] = {\n type: error.error.name,\n message: error.error.message,\n };\n\n return acc;\n }, parsedErrors);\n}\n\n/**\n * Creates a resolver for react-hook-form using computed-types schema validation\n * @param {Schema} schema - The computed-types schema to validate against\n * @returns {Resolver<Type<typeof schema>>} A resolver function compatible with react-hook-form\n * @example\n * const schema = Schema({\n * name: string,\n * age: number\n * });\n *\n * useForm({\n * resolver: computedTypesResolver(schema)\n * });\n */\nexport function computedTypesResolver<\n Input extends FieldValues,\n Context,\n Output,\n>(schema: FunctionType<Output, [Input]>): Resolver<Input, Context, Output> {\n return async (values, _, options) => {\n try {\n const data = await schema(values);\n\n options.shouldUseNativeValidation && validateFieldsNatively({}, options);\n\n return {\n errors: {},\n values: data,\n };\n } catch (error: any) {\n if (isValidationError(error)) {\n return {\n values: {},\n errors: toNestErrors(parseErrorSchema(error), options),\n };\n }\n\n throw error;\n }\n };\n}\n"],"names":["schema","values","_","options","Promise","resolve","then","data","shouldUseNativeValidation","validateFieldsNatively","errors","_catch","error","isValidationError","toNestErrors","computedTypesError","reduce","acc","path","join","type","name","message","e","reject"],"mappings":"2VAkCM,SAIJA,GACA,OAAcC,SAAAA,EAAQC,EAAGC,GAAW,IAAA,OAAAC,QAAAC,gCAC9BD,QAAAC,QACiBL,EAAOC,IAAOK,KAAA,SAA3BC,GAIN,OAFAJ,EAAQK,2BAA6BC,EAAAA,uBAAuB,CAAA,EAAIN,GAEzD,CACLO,OAAQ,CAAA,EACRT,OAAQM,EACR,4DAT8BI,CAAA,EAUjC,SAAQC,GACP,GA7CoB,SAACA,GACzB,OAAgB,MAAhBA,EAAMF,MAAc,CA4CZG,CAAkBD,GACpB,MAAO,CACLX,OAAQ,CAAE,EACVS,OAAQI,gBA7CQC,EA6CsBH,GA3CtCG,EAAmBL,QAAU,IAAIM,OAAO,SAACC,EAAKL,GAMpD,OALAK,EAAIL,EAAMM,KAAKC,KAAK,MAAQ,CAC1BC,KAAMR,EAAMA,MAAMS,KAClBC,QAASV,EAAMA,MAAMU,SAGhBL,CACT,EARkC,CAAE,IA4CkBd,IA7CxD,IAA0BY,EAiDpB,MAAMH,CACR,GACF,CAAC,MAAAW,GAAAnB,OAAAA,QAAAoB,OAAAD,EACH,CAAA,CAAA"}

View file

@ -0,0 +1 @@
export * from './computed-types';

View file

@ -0,0 +1,17 @@
{
"name": "@hookform/resolvers/computed-types",
"amdName": "hookformResolversComputedTypes",
"version": "1.0.0",
"private": true,
"description": "React Hook Form validation resolver: computed-types",
"main": "dist/computed-types.js",
"module": "dist/computed-types.module.js",
"umd:main": "dist/computed-types.umd.js",
"source": "src/index.ts",
"types": "dist/index.d.ts",
"license": "MIT",
"peerDependencies": {
"react-hook-form": "^7.55.0",
"@hookform/resolvers": "^2.0.0"
}
}

View file

@ -0,0 +1,79 @@
import { render, screen } from '@testing-library/react';
import user from '@testing-library/user-event';
import Schema, { Type, string } from 'computed-types';
import React from 'react';
import { useForm } from 'react-hook-form';
import { computedTypesResolver } from '..';
const USERNAME_REQUIRED_MESSAGE = 'username field is required';
const PASSWORD_REQUIRED_MESSAGE = 'password field is required';
const schema = Schema({
username: string.min(2).error(USERNAME_REQUIRED_MESSAGE),
password: string.min(2).error(PASSWORD_REQUIRED_MESSAGE),
});
interface Props {
onSubmit: (data: Type<typeof schema>) => void;
}
function TestComponent({ onSubmit }: Props) {
const { register, handleSubmit } = useForm({
resolver: computedTypesResolver(schema),
shouldUseNativeValidation: true,
});
return (
<form onSubmit={handleSubmit(onSubmit)}>
<input {...register('username')} placeholder="username" />
<input {...register('password')} placeholder="password" />
<button type="submit">submit</button>
</form>
);
}
test("form's native validation with computed-types", async () => {
const handleSubmit = vi.fn();
render(<TestComponent onSubmit={handleSubmit} />);
// username
let usernameField = screen.getByPlaceholderText(
/username/i,
) as HTMLInputElement;
expect(usernameField.validity.valid).toBe(true);
expect(usernameField.validationMessage).toBe('');
// password
let passwordField = screen.getByPlaceholderText(
/password/i,
) as HTMLInputElement;
expect(passwordField.validity.valid).toBe(true);
expect(passwordField.validationMessage).toBe('');
await user.click(screen.getByText(/submit/i));
// username
usernameField = screen.getByPlaceholderText(/username/i) as HTMLInputElement;
expect(usernameField.validity.valid).toBe(false);
expect(usernameField.validationMessage).toBe(USERNAME_REQUIRED_MESSAGE);
// password
passwordField = screen.getByPlaceholderText(/password/i) as HTMLInputElement;
expect(passwordField.validity.valid).toBe(false);
expect(passwordField.validationMessage).toBe(PASSWORD_REQUIRED_MESSAGE);
await user.type(screen.getByPlaceholderText(/username/i), 'joe');
await user.type(screen.getByPlaceholderText(/password/i), 'password');
// username
usernameField = screen.getByPlaceholderText(/username/i) as HTMLInputElement;
expect(usernameField.validity.valid).toBe(true);
expect(usernameField.validationMessage).toBe('');
// password
passwordField = screen.getByPlaceholderText(/password/i) as HTMLInputElement;
expect(passwordField.validity.valid).toBe(true);
expect(passwordField.validationMessage).toBe('');
});

View file

@ -0,0 +1,57 @@
import { render, screen } from '@testing-library/react';
import user from '@testing-library/user-event';
import Schema, { Type, string } from 'computed-types';
import React from 'react';
import { useForm } from 'react-hook-form';
import { computedTypesResolver } from '..';
const schema = Schema({
username: string.min(2).error('username field is required'),
password: string.min(2).error('password field is required'),
address: Schema({
zipCode: string.min(5).max(5).error('zipCode field is required'),
}),
});
function TestComponent({
onSubmit,
}: { onSubmit: (data: Type<typeof schema>) => void }) {
const {
register,
handleSubmit,
formState: { errors },
} = useForm({
resolver: computedTypesResolver(schema), // Useful to check TypeScript regressions
});
return (
<form onSubmit={handleSubmit(onSubmit)}>
<input {...register('username')} />
{errors.username && <span role="alert">{errors.username.message}</span>}
<input {...register('password')} />
{errors.password && <span role="alert">{errors.password.message}</span>}
<input {...register('address.zipCode')} />
{errors.address?.zipCode && (
<span role="alert">{errors.address.zipCode.message}</span>
)}
<button type="submit">submit</button>
</form>
);
}
test("form's validation with computed-types and TypeScript's integration", async () => {
const handleSubmit = vi.fn();
render(<TestComponent onSubmit={handleSubmit} />);
expect(screen.queryAllByRole('alert')).toHaveLength(0);
await user.click(screen.getByText(/submit/i));
expect(screen.getByText(/username field is required/i)).toBeInTheDocument();
expect(screen.getByText(/password field is required/i)).toBeInTheDocument();
expect(screen.getByText(/zipCode field is required/i)).toBeInTheDocument();
expect(handleSubmit).not.toHaveBeenCalled();
});

View file

@ -0,0 +1,86 @@
import Schema, { Type, string, number, array, boolean } from 'computed-types';
import { Field, InternalFieldName } from 'react-hook-form';
export const schema = Schema({
username: string.regexp(/^\w+$/).min(3).max(30),
password: string
.regexp(new RegExp('.*[A-Z].*'), 'One uppercase character')
.regexp(new RegExp('.*[a-z].*'), 'One lowercase character')
.regexp(new RegExp('.*\\d.*'), 'One number')
.regexp(
new RegExp('.*[`~<>?,./!@#$%^&*()\\-_+="\'|{}\\[\\];:\\\\].*'),
'One special character',
)
.min(8, 'Must be at least 8 characters in length'),
repeatPassword: string,
accessToken: Schema.either(string, number).optional(),
birthYear: number.min(1900).max(2013).optional(),
email: string
.regexp(/^[\w-\.]+@([\w-]+\.)+[\w-]{2,4}$/)
.error('Incorrect email'),
tags: array.of(string),
enabled: boolean,
like: array
.of({
id: number,
name: string.min(4).max(4),
})
.optional(),
address: Schema({
city: string.min(3, 'Is required'),
zipCode: string
.min(5, 'Must be 5 characters long')
.max(5, 'Must be 5 characters long'),
}),
});
export const validData: Type<typeof schema> = {
username: 'Doe',
password: 'Password123_',
repeatPassword: 'Password123_',
accessToken: 'accessToken',
birthYear: 2000,
email: 'john@doe.com',
tags: ['tag1', 'tag2'],
enabled: true,
like: [
{
id: 1,
name: 'name',
},
],
address: {
city: 'Awesome city',
zipCode: '12345',
},
};
export const invalidData = {
password: '___',
email: '',
birthYear: 'birthYear',
like: [{ id: 'z' }],
address: {
city: '',
zipCode: '123',
},
} as any as Type<typeof schema>;
export const fields: Record<InternalFieldName, Field['_f']> = {
username: {
ref: { name: 'username' },
name: 'username',
},
password: {
ref: { name: 'password' },
name: 'password',
},
email: {
ref: { name: 'email' },
name: 'email',
},
birthday: {
ref: { name: 'birthday' },
name: 'birthday',
},
};

View file

@ -0,0 +1,74 @@
// Vitest Snapshot v1, https://vitest.dev/guide/snapshot.html
exports[`computedTypesResolver > should return a single error from computedTypesResolver when validation fails 1`] = `
{
"errors": {
"address": {
"city": {
"message": "Is required",
"ref": undefined,
"type": "ValidationError",
},
"zipCode": {
"message": "Must be 5 characters long",
"ref": undefined,
"type": "ValidationError",
},
},
"birthYear": {
"message": "Expect value to be "number"",
"ref": undefined,
"type": "ValidationError",
},
"email": {
"message": "Incorrect email",
"ref": {
"name": "email",
},
"type": "ValidationError",
},
"enabled": {
"message": "Expect value to be "boolean"",
"ref": undefined,
"type": "ValidationError",
},
"like": {
"id": {
"message": "Expect value to be "number"",
"ref": undefined,
"type": "ValidationError",
},
"name": {
"message": "Expect value to be "string"",
"ref": undefined,
"type": "ValidationError",
},
},
"password": {
"message": "One uppercase character",
"ref": {
"name": "password",
},
"type": "ValidationError",
},
"repeatPassword": {
"message": "Expect value to be "string"",
"ref": undefined,
"type": "ValidationError",
},
"tags": {
"message": "Expecting value to be an array",
"ref": undefined,
"type": "ValidationError",
},
"username": {
"message": "Expect value to be "string"",
"ref": {
"name": "username",
},
"type": "ValidationError",
},
},
"values": {},
}
`;

View file

@ -0,0 +1,96 @@
import Schema, { number } from 'computed-types';
import { Resolver, SubmitHandler, useForm } from 'react-hook-form';
import { computedTypesResolver } from '..';
import { fields, invalidData, schema, validData } from './__fixtures__/data';
const shouldUseNativeValidation = false;
describe('computedTypesResolver', () => {
it('should return values from computedTypesResolver when validation pass', async () => {
const result = await computedTypesResolver(schema)(validData, undefined, {
fields,
shouldUseNativeValidation,
});
expect(result).toEqual({ errors: {}, values: validData });
});
it('should return a single error from computedTypesResolver when validation fails', async () => {
const result = await computedTypesResolver(schema)(invalidData, undefined, {
fields,
shouldUseNativeValidation,
});
expect(result).toMatchSnapshot();
});
it('should throw any error unrelated to computed-types', async () => {
const schemaWithCustomError = schema.transform(() => {
throw Error('custom error');
});
const promise = computedTypesResolver(schemaWithCustomError)(
validData,
undefined,
{
fields,
shouldUseNativeValidation,
},
);
await expect(promise).rejects.toThrow('custom error');
});
/**
* Type inference tests
*/
it('should correctly infer the output type from a computedTypes schema', () => {
const resolver = computedTypesResolver(Schema({ id: number }));
expectTypeOf(resolver).toEqualTypeOf<
Resolver<{ id: number }, unknown, { id: number }>
>();
});
it('should correctly infer the output type from a computedTypes schema using a transform', () => {
const resolver = computedTypesResolver(
Schema({ id: number.transform((val) => String(val)) }),
);
expectTypeOf(resolver).toEqualTypeOf<
Resolver<{ id: number }, unknown, { id: string }>
>();
});
it('should correctly infer the output type from a computedTypes schema for the handleSubmit function in useForm', () => {
const schema = Schema({ id: number });
const form = useForm({
resolver: computedTypesResolver(schema),
});
expectTypeOf(form.watch('id')).toEqualTypeOf<number>();
expectTypeOf(form.handleSubmit).parameter(0).toEqualTypeOf<
SubmitHandler<{
id: number;
}>
>();
});
it('should correctly infer the output type from a computedTypes schema with a transform for the handleSubmit function in useForm', () => {
const schema = Schema({ id: number.transform((val) => String(val)) });
const form = useForm({
resolver: computedTypesResolver(schema),
});
expectTypeOf(form.watch('id')).toEqualTypeOf<number>();
expectTypeOf(form.handleSubmit).parameter(0).toEqualTypeOf<
SubmitHandler<{
id: string;
}>
>();
});
});

View file

@ -0,0 +1,61 @@
import { toNestErrors, validateFieldsNatively } from '@hookform/resolvers';
import { ValidationError } from 'computed-types';
import FunctionType from 'computed-types/lib/schema/FunctionType';
import type { FieldErrors, FieldValues, Resolver } from 'react-hook-form';
const isValidationError = (error: any): error is ValidationError =>
error.errors != null;
function parseErrorSchema(computedTypesError: ValidationError) {
const parsedErrors: FieldErrors = {};
return (computedTypesError.errors || []).reduce((acc, error) => {
acc[error.path.join('.')] = {
type: error.error.name,
message: error.error.message,
};
return acc;
}, parsedErrors);
}
/**
* Creates a resolver for react-hook-form using computed-types schema validation
* @param {Schema} schema - The computed-types schema to validate against
* @returns {Resolver<Type<typeof schema>>} A resolver function compatible with react-hook-form
* @example
* const schema = Schema({
* name: string,
* age: number
* });
*
* useForm({
* resolver: computedTypesResolver(schema)
* });
*/
export function computedTypesResolver<
Input extends FieldValues,
Context,
Output,
>(schema: FunctionType<Output, [Input]>): Resolver<Input, Context, Output> {
return async (values, _, options) => {
try {
const data = await schema(values);
options.shouldUseNativeValidation && validateFieldsNatively({}, options);
return {
errors: {},
values: data,
};
} catch (error: any) {
if (isValidationError(error)) {
return {
values: {},
errors: toNestErrors(parseErrorSchema(error), options),
};
}
throw error;
}
};
}

View file

@ -0,0 +1 @@
export * from './computed-types';

2
node_modules/@hookform/resolvers/dist/index.d.ts generated vendored Normal file
View file

@ -0,0 +1,2 @@
export * from './toNestErrors';
export * from './validateFieldsNatively';

2
node_modules/@hookform/resolvers/dist/resolvers.js generated vendored Normal file
View file

@ -0,0 +1,2 @@
var e=require("react-hook-form"),r=function(r,t,i){if(r&&"reportValidity"in r){var n=e.get(i,t);r.setCustomValidity(n&&n.message||""),r.reportValidity()}},t=function(e,t){var i=function(i){var n=t.fields[i];n&&n.ref&&"reportValidity"in n.ref?r(n.ref,i,e):n&&n.refs&&n.refs.forEach(function(t){return r(t,i,e)})};for(var n in t.fields)i(n)},i=function(e,r){var t=n(r);return e.some(function(e){return n(e).match("^"+t+"\\.\\d+")})};function n(e){return e.replace(/\]|\[/g,"")}exports.toNestErrors=function(r,n){n.shouldUseNativeValidation&&t(r,n);var a={};for(var o in r){var s=e.get(n.fields,o),f=Object.assign(r[o]||{},{ref:s&&s.ref});if(i(n.names||Object.keys(r),o)){var u=Object.assign({},e.get(a,o));e.set(u,"root",f),e.set(a,o,u)}else e.set(a,o,f)}return a},exports.validateFieldsNatively=t;
//# sourceMappingURL=resolvers.js.map

View file

@ -0,0 +1 @@
{"version":3,"file":"resolvers.js","sources":["../src/validateFieldsNatively.ts","../src/toNestErrors.ts"],"sourcesContent":["import {\n FieldError,\n FieldErrors,\n FieldValues,\n Ref,\n ResolverOptions,\n get,\n} from 'react-hook-form';\n\nconst setCustomValidity = (\n ref: Ref,\n fieldPath: string,\n errors: FieldErrors,\n) => {\n if (ref && 'reportValidity' in ref) {\n const error = get(errors, fieldPath) as FieldError | undefined;\n ref.setCustomValidity((error && error.message) || '');\n\n ref.reportValidity();\n }\n};\n\n// Native validation (web only)\nexport const validateFieldsNatively = <TFieldValues extends FieldValues>(\n errors: FieldErrors,\n options: ResolverOptions<TFieldValues>,\n): void => {\n for (const fieldPath in options.fields) {\n const field = options.fields[fieldPath];\n if (field && field.ref && 'reportValidity' in field.ref) {\n setCustomValidity(field.ref, fieldPath, errors);\n } else if (field && field.refs) {\n field.refs.forEach((ref: HTMLInputElement) =>\n setCustomValidity(ref, fieldPath, errors),\n );\n }\n }\n};\n","import {\n Field,\n FieldErrors,\n FieldValues,\n InternalFieldName,\n ResolverOptions,\n get,\n set,\n} from 'react-hook-form';\nimport { validateFieldsNatively } from './validateFieldsNatively';\n\nexport const toNestErrors = <TFieldValues extends FieldValues>(\n errors: FieldErrors,\n options: ResolverOptions<TFieldValues>,\n): FieldErrors<TFieldValues> => {\n options.shouldUseNativeValidation && validateFieldsNatively(errors, options);\n\n const fieldErrors = {} as FieldErrors<TFieldValues>;\n for (const path in errors) {\n const field = get(options.fields, path) as Field['_f'] | undefined;\n const error = Object.assign(errors[path] || {}, {\n ref: field && field.ref,\n });\n\n if (isNameInFieldArray(options.names || Object.keys(errors), path)) {\n const fieldArrayErrors = Object.assign({}, get(fieldErrors, path));\n\n set(fieldArrayErrors, 'root', error);\n set(fieldErrors, path, fieldArrayErrors);\n } else {\n set(fieldErrors, path, error);\n }\n }\n\n return fieldErrors;\n};\n\nconst isNameInFieldArray = (\n names: InternalFieldName[],\n name: InternalFieldName,\n) => {\n const path = escapeBrackets(name);\n return names.some((n) => escapeBrackets(n).match(`^${path}\\\\.\\\\d+`));\n};\n\n/**\n * Escapes special characters in a string to be used in a regex pattern.\n * it removes the brackets from the string to match the `set` method.\n *\n * @param input - The input string to escape.\n * @returns The escaped string.\n */\nfunction escapeBrackets(input: string): string {\n return input.replace(/\\]|\\[/g, '');\n}\n"],"names":["setCustomValidity","ref","fieldPath","errors","error","get","message","reportValidity","validateFieldsNatively","options","_loop","field","fields","refs","forEach","isNameInFieldArray","names","name","path","escapeBrackets","some","n","match","input","replace","shouldUseNativeValidation","fieldErrors","Object","assign","keys","fieldArrayErrors","set"],"mappings":"iCASMA,EAAoB,SACxBC,EACAC,EACAC,GAEA,GAAIF,GAAO,mBAAoBA,EAAK,CAClC,IAAMG,EAAQC,MAAIF,EAAQD,GAC1BD,EAAID,kBAAmBI,GAASA,EAAME,SAAY,IAElDL,EAAIM,gBACN,CACF,EAGaC,EAAyB,SACpCL,EACAM,GACQC,IAAAA,WAAAR,GAEN,IAAMS,EAAQF,EAAQG,OAAOV,GACzBS,GAASA,EAAMV,KAAO,mBAAoBU,EAAMV,IAClDD,EAAkBW,EAAMV,IAAKC,EAAWC,GAC/BQ,GAASA,EAAME,MACxBF,EAAME,KAAKC,QAAQ,SAACb,UAClBD,EAAkBC,EAAKC,EAAWC,EAAO,EAG/C,EATA,IAAK,IAAMD,KAAaO,EAAQG,OAAMF,EAAAR,EAUxC,ECAMa,EAAqB,SACzBC,EACAC,GAEA,IAAMC,EAAOC,EAAeF,GAC5B,OAAOD,EAAMI,KAAK,SAACC,GAAM,OAAAF,EAAeE,GAAGC,MAAK,IAAKJ,EAAI,UAAU,EACrE,EASA,SAASC,EAAeI,GACtB,OAAOA,EAAMC,QAAQ,SAAU,GACjC,sBA3C4B,SAC1BrB,EACAM,GAEAA,EAAQgB,2BAA6BjB,EAAuBL,EAAQM,GAEpE,IAAMiB,EAAc,CAA+B,EACnD,IAAK,IAAMR,KAAQf,EAAQ,CACzB,IAAMQ,EAAQN,EAAGA,IAACI,EAAQG,OAAQM,GAC5Bd,EAAQuB,OAAOC,OAAOzB,EAAOe,IAAS,GAAI,CAC9CjB,IAAKU,GAASA,EAAMV,MAGtB,GAAIc,EAAmBN,EAAQO,OAASW,OAAOE,KAAK1B,GAASe,GAAO,CAClE,IAAMY,EAAmBH,OAAOC,OAAO,CAAE,EAAEvB,EAAGA,IAACqB,EAAaR,IAE5Da,MAAID,EAAkB,OAAQ1B,GAC9B2B,MAAIL,EAAaR,EAAMY,EACzB,MACEC,EAAGA,IAACL,EAAaR,EAAMd,EAE3B,CAEA,OAAOsB,CACT"}

2
node_modules/@hookform/resolvers/dist/resolvers.mjs generated vendored Normal file
View file

@ -0,0 +1,2 @@
import{get as e,set as t}from"react-hook-form";const r=(t,r,o)=>{if(t&&"reportValidity"in t){const s=e(o,r);t.setCustomValidity(s&&s.message||""),t.reportValidity()}},o=(e,t)=>{for(const o in t.fields){const s=t.fields[o];s&&s.ref&&"reportValidity"in s.ref?r(s.ref,o,e):s&&s.refs&&s.refs.forEach(t=>r(t,o,e))}},s=(r,s)=>{s.shouldUseNativeValidation&&o(r,s);const n={};for(const o in r){const f=e(s.fields,o),c=Object.assign(r[o]||{},{ref:f&&f.ref});if(i(s.names||Object.keys(r),o)){const r=Object.assign({},e(n,o));t(r,"root",c),t(n,o,r)}else t(n,o,c)}return n},i=(e,t)=>{const r=n(t);return e.some(e=>n(e).match(`^${r}\\.\\d+`))};function n(e){return e.replace(/\]|\[/g,"")}export{s as toNestErrors,o as validateFieldsNatively};
//# sourceMappingURL=resolvers.mjs.map

View file

@ -0,0 +1 @@
{"version":3,"file":"resolvers.mjs","sources":["../src/validateFieldsNatively.ts","../src/toNestErrors.ts"],"sourcesContent":["import {\n FieldError,\n FieldErrors,\n FieldValues,\n Ref,\n ResolverOptions,\n get,\n} from 'react-hook-form';\n\nconst setCustomValidity = (\n ref: Ref,\n fieldPath: string,\n errors: FieldErrors,\n) => {\n if (ref && 'reportValidity' in ref) {\n const error = get(errors, fieldPath) as FieldError | undefined;\n ref.setCustomValidity((error && error.message) || '');\n\n ref.reportValidity();\n }\n};\n\n// Native validation (web only)\nexport const validateFieldsNatively = <TFieldValues extends FieldValues>(\n errors: FieldErrors,\n options: ResolverOptions<TFieldValues>,\n): void => {\n for (const fieldPath in options.fields) {\n const field = options.fields[fieldPath];\n if (field && field.ref && 'reportValidity' in field.ref) {\n setCustomValidity(field.ref, fieldPath, errors);\n } else if (field && field.refs) {\n field.refs.forEach((ref: HTMLInputElement) =>\n setCustomValidity(ref, fieldPath, errors),\n );\n }\n }\n};\n","import {\n Field,\n FieldErrors,\n FieldValues,\n InternalFieldName,\n ResolverOptions,\n get,\n set,\n} from 'react-hook-form';\nimport { validateFieldsNatively } from './validateFieldsNatively';\n\nexport const toNestErrors = <TFieldValues extends FieldValues>(\n errors: FieldErrors,\n options: ResolverOptions<TFieldValues>,\n): FieldErrors<TFieldValues> => {\n options.shouldUseNativeValidation && validateFieldsNatively(errors, options);\n\n const fieldErrors = {} as FieldErrors<TFieldValues>;\n for (const path in errors) {\n const field = get(options.fields, path) as Field['_f'] | undefined;\n const error = Object.assign(errors[path] || {}, {\n ref: field && field.ref,\n });\n\n if (isNameInFieldArray(options.names || Object.keys(errors), path)) {\n const fieldArrayErrors = Object.assign({}, get(fieldErrors, path));\n\n set(fieldArrayErrors, 'root', error);\n set(fieldErrors, path, fieldArrayErrors);\n } else {\n set(fieldErrors, path, error);\n }\n }\n\n return fieldErrors;\n};\n\nconst isNameInFieldArray = (\n names: InternalFieldName[],\n name: InternalFieldName,\n) => {\n const path = escapeBrackets(name);\n return names.some((n) => escapeBrackets(n).match(`^${path}\\\\.\\\\d+`));\n};\n\n/**\n * Escapes special characters in a string to be used in a regex pattern.\n * it removes the brackets from the string to match the `set` method.\n *\n * @param input - The input string to escape.\n * @returns The escaped string.\n */\nfunction escapeBrackets(input: string): string {\n return input.replace(/\\]|\\[/g, '');\n}\n"],"names":["setCustomValidity","ref","fieldPath","errors","error","get","message","reportValidity","validateFieldsNatively","options","fields","field","refs","forEach","toNestErrors","shouldUseNativeValidation","fieldErrors","path","Object","assign","isNameInFieldArray","names","keys","fieldArrayErrors","set","name","escapeBrackets","some","n","match","input","replace"],"mappings":"+CASA,MAAMA,EAAoBA,CACxBC,EACAC,EACAC,KAEA,GAAIF,GAAO,mBAAoBA,EAAK,CAClC,MAAMG,EAAQC,EAAIF,EAAQD,GAC1BD,EAAID,kBAAmBI,GAASA,EAAME,SAAY,IAElDL,EAAIM,gBACN,GAIWC,EAAyBA,CACpCL,EACAM,KAEA,IAAK,MAAMP,KAAaO,EAAQC,OAAQ,CACtC,MAAMC,EAAQF,EAAQC,OAAOR,GACzBS,GAASA,EAAMV,KAAO,mBAAoBU,EAAMV,IAClDD,EAAkBW,EAAMV,IAAKC,EAAWC,GAC/BQ,GAASA,EAAMC,MACxBD,EAAMC,KAAKC,QAASZ,GAClBD,EAAkBC,EAAKC,EAAWC,GAGxC,GCzBWW,EAAeA,CAC1BX,EACAM,KAEAA,EAAQM,2BAA6BP,EAAuBL,EAAQM,GAEpE,MAAMO,EAAc,GACpB,IAAK,MAAMC,KAAQd,EAAQ,CACzB,MAAMQ,EAAQN,EAAII,EAAQC,OAAQO,GAC5Bb,EAAQc,OAAOC,OAAOhB,EAAOc,IAAS,CAAA,EAAI,CAC9ChB,IAAKU,GAASA,EAAMV,MAGtB,GAAImB,EAAmBX,EAAQY,OAASH,OAAOI,KAAKnB,GAASc,GAAO,CAClE,MAAMM,EAAmBL,OAAOC,OAAO,CAAA,EAAId,EAAIW,EAAaC,IAE5DO,EAAID,EAAkB,OAAQnB,GAC9BoB,EAAIR,EAAaC,EAAMM,EACzB,MACEC,EAAIR,EAAaC,EAAMb,EAE3B,CAEA,OAAOY,GAGHI,EAAqBA,CACzBC,EACAI,KAEA,MAAMR,EAAOS,EAAeD,GAC5B,OAAOJ,EAAMM,KAAMC,GAAMF,EAAeE,GAAGC,MAAM,IAAIZ,YAAc,EAUrE,SAASS,EAAeI,GACtB,OAAOA,EAAMC,QAAQ,SAAU,GACjC"}

View file

@ -0,0 +1,2 @@
import{get as r,set as e}from"react-hook-form";var t=function(e,t,i){if(e&&"reportValidity"in e){var n=r(i,t);e.setCustomValidity(n&&n.message||""),e.reportValidity()}},i=function(r,e){var i=function(i){var n=e.fields[i];n&&n.ref&&"reportValidity"in n.ref?t(n.ref,i,r):n&&n.refs&&n.refs.forEach(function(e){return t(e,i,r)})};for(var n in e.fields)i(n)},n=function(t,n){n.shouldUseNativeValidation&&i(t,n);var a={};for(var f in t){var s=r(n.fields,f),c=Object.assign(t[f]||{},{ref:s&&s.ref});if(o(n.names||Object.keys(t),f)){var u=Object.assign({},r(a,f));e(u,"root",c),e(a,f,u)}else e(a,f,c)}return a},o=function(r,e){var t=a(e);return r.some(function(r){return a(r).match("^"+t+"\\.\\d+")})};function a(r){return r.replace(/\]|\[/g,"")}export{n as toNestErrors,i as validateFieldsNatively};
//# sourceMappingURL=resolvers.module.js.map

View file

@ -0,0 +1 @@
{"version":3,"file":"resolvers.module.js","sources":["../src/validateFieldsNatively.ts","../src/toNestErrors.ts"],"sourcesContent":["import {\n FieldError,\n FieldErrors,\n FieldValues,\n Ref,\n ResolverOptions,\n get,\n} from 'react-hook-form';\n\nconst setCustomValidity = (\n ref: Ref,\n fieldPath: string,\n errors: FieldErrors,\n) => {\n if (ref && 'reportValidity' in ref) {\n const error = get(errors, fieldPath) as FieldError | undefined;\n ref.setCustomValidity((error && error.message) || '');\n\n ref.reportValidity();\n }\n};\n\n// Native validation (web only)\nexport const validateFieldsNatively = <TFieldValues extends FieldValues>(\n errors: FieldErrors,\n options: ResolverOptions<TFieldValues>,\n): void => {\n for (const fieldPath in options.fields) {\n const field = options.fields[fieldPath];\n if (field && field.ref && 'reportValidity' in field.ref) {\n setCustomValidity(field.ref, fieldPath, errors);\n } else if (field && field.refs) {\n field.refs.forEach((ref: HTMLInputElement) =>\n setCustomValidity(ref, fieldPath, errors),\n );\n }\n }\n};\n","import {\n Field,\n FieldErrors,\n FieldValues,\n InternalFieldName,\n ResolverOptions,\n get,\n set,\n} from 'react-hook-form';\nimport { validateFieldsNatively } from './validateFieldsNatively';\n\nexport const toNestErrors = <TFieldValues extends FieldValues>(\n errors: FieldErrors,\n options: ResolverOptions<TFieldValues>,\n): FieldErrors<TFieldValues> => {\n options.shouldUseNativeValidation && validateFieldsNatively(errors, options);\n\n const fieldErrors = {} as FieldErrors<TFieldValues>;\n for (const path in errors) {\n const field = get(options.fields, path) as Field['_f'] | undefined;\n const error = Object.assign(errors[path] || {}, {\n ref: field && field.ref,\n });\n\n if (isNameInFieldArray(options.names || Object.keys(errors), path)) {\n const fieldArrayErrors = Object.assign({}, get(fieldErrors, path));\n\n set(fieldArrayErrors, 'root', error);\n set(fieldErrors, path, fieldArrayErrors);\n } else {\n set(fieldErrors, path, error);\n }\n }\n\n return fieldErrors;\n};\n\nconst isNameInFieldArray = (\n names: InternalFieldName[],\n name: InternalFieldName,\n) => {\n const path = escapeBrackets(name);\n return names.some((n) => escapeBrackets(n).match(`^${path}\\\\.\\\\d+`));\n};\n\n/**\n * Escapes special characters in a string to be used in a regex pattern.\n * it removes the brackets from the string to match the `set` method.\n *\n * @param input - The input string to escape.\n * @returns The escaped string.\n */\nfunction escapeBrackets(input: string): string {\n return input.replace(/\\]|\\[/g, '');\n}\n"],"names":["setCustomValidity","ref","fieldPath","errors","error","get","message","reportValidity","validateFieldsNatively","options","_loop","field","fields","refs","forEach","toNestErrors","shouldUseNativeValidation","fieldErrors","path","Object","assign","isNameInFieldArray","names","keys","fieldArrayErrors","set","name","escapeBrackets","some","n","match","input","replace"],"mappings":"+CASA,IAAMA,EAAoB,SACxBC,EACAC,EACAC,GAEA,GAAIF,GAAO,mBAAoBA,EAAK,CAClC,IAAMG,EAAQC,EAAIF,EAAQD,GAC1BD,EAAID,kBAAmBI,GAASA,EAAME,SAAY,IAElDL,EAAIM,gBACN,CACF,EAGaC,EAAyB,SACpCL,EACAM,GACQC,IAAAA,WAAAR,GAEN,IAAMS,EAAQF,EAAQG,OAAOV,GACzBS,GAASA,EAAMV,KAAO,mBAAoBU,EAAMV,IAClDD,EAAkBW,EAAMV,IAAKC,EAAWC,GAC/BQ,GAASA,EAAME,MACxBF,EAAME,KAAKC,QAAQ,SAACb,UAClBD,EAAkBC,EAAKC,EAAWC,EAAO,EAG/C,EATA,IAAK,IAAMD,KAAaO,EAAQG,OAAMF,EAAAR,EAUxC,EC1Baa,EAAe,SAC1BZ,EACAM,GAEAA,EAAQO,2BAA6BR,EAAuBL,EAAQM,GAEpE,IAAMQ,EAAc,CAA+B,EACnD,IAAK,IAAMC,KAAQf,EAAQ,CACzB,IAAMQ,EAAQN,EAAII,EAAQG,OAAQM,GAC5Bd,EAAQe,OAAOC,OAAOjB,EAAOe,IAAS,GAAI,CAC9CjB,IAAKU,GAASA,EAAMV,MAGtB,GAAIoB,EAAmBZ,EAAQa,OAASH,OAAOI,KAAKpB,GAASe,GAAO,CAClE,IAAMM,EAAmBL,OAAOC,OAAO,CAAE,EAAEf,EAAIY,EAAaC,IAE5DO,EAAID,EAAkB,OAAQpB,GAC9BqB,EAAIR,EAAaC,EAAMM,EACzB,MACEC,EAAIR,EAAaC,EAAMd,EAE3B,CAEA,OAAOa,CACT,EAEMI,EAAqB,SACzBC,EACAI,GAEA,IAAMR,EAAOS,EAAeD,GAC5B,OAAOJ,EAAMM,KAAK,SAACC,GAAM,OAAAF,EAAeE,GAAGC,MAAK,IAAKZ,EAAI,UAAU,EACrE,EASA,SAASS,EAAeI,GACtB,OAAOA,EAAMC,QAAQ,SAAU,GACjC"}

View file

@ -0,0 +1,2 @@
!function(e,t){"object"==typeof exports&&"undefined"!=typeof module?t(exports,require("react-hook-form")):"function"==typeof define&&define.amd?define(["exports","react-hook-form"],t):t((e||self).hookformResolvers={},e.ReactHookForm)}(this,function(e,t){var r=function(e,r,o){if(e&&"reportValidity"in e){var i=t.get(o,r);e.setCustomValidity(i&&i.message||""),e.reportValidity()}},o=function(e,t){var o=function(o){var i=t.fields[o];i&&i.ref&&"reportValidity"in i.ref?r(i.ref,o,e):i&&i.refs&&i.refs.forEach(function(t){return r(t,o,e)})};for(var i in t.fields)o(i)},i=function(e,t){var r=n(t);return e.some(function(e){return n(e).match("^"+r+"\\.\\d+")})};function n(e){return e.replace(/\]|\[/g,"")}e.toNestErrors=function(e,r){r.shouldUseNativeValidation&&o(e,r);var n={};for(var f in e){var s=t.get(r.fields,f),a=Object.assign(e[f]||{},{ref:s&&s.ref});if(i(r.names||Object.keys(e),f)){var u=Object.assign({},t.get(n,f));t.set(u,"root",a),t.set(n,f,u)}else t.set(n,f,a)}return n},e.validateFieldsNatively=o});
//# sourceMappingURL=resolvers.umd.js.map

View file

@ -0,0 +1 @@
{"version":3,"file":"resolvers.umd.js","sources":["../src/validateFieldsNatively.ts","../src/toNestErrors.ts"],"sourcesContent":["import {\n FieldError,\n FieldErrors,\n FieldValues,\n Ref,\n ResolverOptions,\n get,\n} from 'react-hook-form';\n\nconst setCustomValidity = (\n ref: Ref,\n fieldPath: string,\n errors: FieldErrors,\n) => {\n if (ref && 'reportValidity' in ref) {\n const error = get(errors, fieldPath) as FieldError | undefined;\n ref.setCustomValidity((error && error.message) || '');\n\n ref.reportValidity();\n }\n};\n\n// Native validation (web only)\nexport const validateFieldsNatively = <TFieldValues extends FieldValues>(\n errors: FieldErrors,\n options: ResolverOptions<TFieldValues>,\n): void => {\n for (const fieldPath in options.fields) {\n const field = options.fields[fieldPath];\n if (field && field.ref && 'reportValidity' in field.ref) {\n setCustomValidity(field.ref, fieldPath, errors);\n } else if (field && field.refs) {\n field.refs.forEach((ref: HTMLInputElement) =>\n setCustomValidity(ref, fieldPath, errors),\n );\n }\n }\n};\n","import {\n Field,\n FieldErrors,\n FieldValues,\n InternalFieldName,\n ResolverOptions,\n get,\n set,\n} from 'react-hook-form';\nimport { validateFieldsNatively } from './validateFieldsNatively';\n\nexport const toNestErrors = <TFieldValues extends FieldValues>(\n errors: FieldErrors,\n options: ResolverOptions<TFieldValues>,\n): FieldErrors<TFieldValues> => {\n options.shouldUseNativeValidation && validateFieldsNatively(errors, options);\n\n const fieldErrors = {} as FieldErrors<TFieldValues>;\n for (const path in errors) {\n const field = get(options.fields, path) as Field['_f'] | undefined;\n const error = Object.assign(errors[path] || {}, {\n ref: field && field.ref,\n });\n\n if (isNameInFieldArray(options.names || Object.keys(errors), path)) {\n const fieldArrayErrors = Object.assign({}, get(fieldErrors, path));\n\n set(fieldArrayErrors, 'root', error);\n set(fieldErrors, path, fieldArrayErrors);\n } else {\n set(fieldErrors, path, error);\n }\n }\n\n return fieldErrors;\n};\n\nconst isNameInFieldArray = (\n names: InternalFieldName[],\n name: InternalFieldName,\n) => {\n const path = escapeBrackets(name);\n return names.some((n) => escapeBrackets(n).match(`^${path}\\\\.\\\\d+`));\n};\n\n/**\n * Escapes special characters in a string to be used in a regex pattern.\n * it removes the brackets from the string to match the `set` method.\n *\n * @param input - The input string to escape.\n * @returns The escaped string.\n */\nfunction escapeBrackets(input: string): string {\n return input.replace(/\\]|\\[/g, '');\n}\n"],"names":["setCustomValidity","ref","fieldPath","errors","error","get","message","reportValidity","validateFieldsNatively","options","_loop","field","fields","refs","forEach","isNameInFieldArray","names","name","path","escapeBrackets","some","n","match","input","replace","shouldUseNativeValidation","fieldErrors","Object","assign","keys","fieldArrayErrors","set"],"mappings":"0SASA,IAAMA,EAAoB,SACxBC,EACAC,EACAC,GAEA,GAAIF,GAAO,mBAAoBA,EAAK,CAClC,IAAMG,EAAQC,MAAIF,EAAQD,GAC1BD,EAAID,kBAAmBI,GAASA,EAAME,SAAY,IAElDL,EAAIM,gBACN,CACF,EAGaC,EAAyB,SACpCL,EACAM,GACQC,IAAAA,WAAAR,GAEN,IAAMS,EAAQF,EAAQG,OAAOV,GACzBS,GAASA,EAAMV,KAAO,mBAAoBU,EAAMV,IAClDD,EAAkBW,EAAMV,IAAKC,EAAWC,GAC/BQ,GAASA,EAAME,MACxBF,EAAME,KAAKC,QAAQ,SAACb,UAClBD,EAAkBC,EAAKC,EAAWC,EAAO,EAG/C,EATA,IAAK,IAAMD,KAAaO,EAAQG,OAAMF,EAAAR,EAUxC,ECAMa,EAAqB,SACzBC,EACAC,GAEA,IAAMC,EAAOC,EAAeF,GAC5B,OAAOD,EAAMI,KAAK,SAACC,GAAM,OAAAF,EAAeE,GAAGC,MAAK,IAAKJ,EAAI,UAAU,EACrE,EASA,SAASC,EAAeI,GACtB,OAAOA,EAAMC,QAAQ,SAAU,GACjC,gBA3C4B,SAC1BrB,EACAM,GAEAA,EAAQgB,2BAA6BjB,EAAuBL,EAAQM,GAEpE,IAAMiB,EAAc,CAA+B,EACnD,IAAK,IAAMR,KAAQf,EAAQ,CACzB,IAAMQ,EAAQN,EAAGA,IAACI,EAAQG,OAAQM,GAC5Bd,EAAQuB,OAAOC,OAAOzB,EAAOe,IAAS,GAAI,CAC9CjB,IAAKU,GAASA,EAAMV,MAGtB,GAAIc,EAAmBN,EAAQO,OAASW,OAAOE,KAAK1B,GAASe,GAAO,CAClE,IAAMY,EAAmBH,OAAOC,OAAO,CAAE,EAAEvB,EAAGA,IAACqB,EAAaR,IAE5Da,MAAID,EAAkB,OAAQ1B,GAC9B2B,MAAIL,EAAaR,EAAMY,EACzB,MACEC,EAAGA,IAACL,EAAaR,EAAMd,EAE3B,CAEA,OAAOsB,CACT"}

View file

@ -0,0 +1,2 @@
import { FieldErrors, FieldValues, ResolverOptions } from 'react-hook-form';
export declare const toNestErrors: <TFieldValues extends FieldValues>(errors: FieldErrors, options: ResolverOptions<TFieldValues>) => FieldErrors<TFieldValues>;

Some files were not shown because too many files have changed in this diff Show more