Added form validators
This commit is contained in:
@@ -0,0 +1,172 @@
|
||||
'use client'
|
||||
|
||||
import { useState, useCallback, useRef, useMemo } from 'react'
|
||||
|
||||
/**
|
||||
* Error map: a field key → its error message. A field is "in error" iff it has
|
||||
* a key here, so `errors.email` is both the truthy flag (for a red border) AND
|
||||
* the message (to display). Empty object = valid.
|
||||
*/
|
||||
export type FormErrors<T> = Partial<Record<keyof T, string>>
|
||||
|
||||
/**
|
||||
* The project's server action that calls submitForm (server-only, holds the
|
||||
* Turnstile secret). This hook is a client hook, so it can't call submitForm
|
||||
* directly — the project injects its action. The result only needs `success`
|
||||
* plus an optional `message`; richer shapes (SubmitFormResult) satisfy it.
|
||||
*/
|
||||
export type FormSubmitAction<T> = (
|
||||
values: T,
|
||||
turnstileToken?: string,
|
||||
) => Promise<{ success: boolean; message?: string }>
|
||||
|
||||
/** Turns the current values into an error map. Empty map = valid. */
|
||||
export type Validator<T> = (values: T) => FormErrors<T>
|
||||
|
||||
type UseFormOptions<T extends Record<string, unknown>> = {
|
||||
/** Defines the field set AND the reset state. Any shape you like. */
|
||||
initialValues: T
|
||||
submitAction: FormSubmitAction<T>
|
||||
/** Project-owned validation. Compose one with `buildValidator` + rules, or write your own. */
|
||||
validate?: Validator<T>
|
||||
/** Require a Turnstile token before submit (when the widget is shown). */
|
||||
requireTurnstile?: boolean
|
||||
/** Generic error message shown when the action fails/throws with no message. */
|
||||
errorFallback?: string
|
||||
/** Clear a field's error as soon as the user edits it. Default true. */
|
||||
clearErrorOnChange?: boolean
|
||||
}
|
||||
|
||||
/**
|
||||
* Fully generic form engine: state, validation, Turnstile token, submit,
|
||||
* success/error — WITHOUT any markup. The project owns 100% of the look AND
|
||||
* the field set: there is no baked-in shape here. Replaces the identical
|
||||
* ~150 lines of form plumbing copied into every project.
|
||||
*
|
||||
* The field set comes from `initialValues`; the rules come from `validate`
|
||||
* (so dynamic/builder-driven forms just build both at runtime). For the
|
||||
* everyday contact form use the `useContactForm` preset instead — it wires
|
||||
* the standard fields and rules for you.
|
||||
*
|
||||
* const f = useForm({
|
||||
* initialValues: { email: '', message: '' },
|
||||
* submitAction, // your server action
|
||||
* validate: buildValidator({ email: [required(), email()], message: [required()] }),
|
||||
* requireTurnstile: Boolean(siteKey),
|
||||
* })
|
||||
* <input value={f.values.email}
|
||||
* onChange={(e) => f.setField('email', e.target.value)}
|
||||
* className={f.errors.email ? 'border-red-500' : '…'} />
|
||||
* <form onSubmit={f.handleSubmit}>…</form>
|
||||
*/
|
||||
export function useForm<T extends Record<string, unknown>>(options: UseFormOptions<T>) {
|
||||
const {
|
||||
initialValues,
|
||||
submitAction,
|
||||
validate,
|
||||
requireTurnstile = false,
|
||||
errorFallback = 'Something went wrong. Please try again.',
|
||||
clearErrorOnChange = true,
|
||||
} = options
|
||||
|
||||
// Freeze the initial snapshot so `reset` is stable even though callers pass a
|
||||
// fresh object literal every render.
|
||||
const initialRef = useRef(initialValues)
|
||||
|
||||
const [values, setValues] = useState<T>(initialRef.current)
|
||||
const [errors, setErrors] = useState<FormErrors<T>>({})
|
||||
const [isSubmitting, setIsSubmitting] = useState(false)
|
||||
const [isSuccess, setIsSuccess] = useState(false)
|
||||
const [errorMessage, setErrorMessage] = useState<string | null>(null)
|
||||
const [turnstileToken, setTurnstileToken] = useState<string | null>(null)
|
||||
|
||||
const setField = useCallback(
|
||||
<K extends keyof T>(key: K, value: T[K]) => {
|
||||
setValues((prev) => ({ ...prev, [key]: value }))
|
||||
if (clearErrorOnChange) {
|
||||
setErrors((prev) => {
|
||||
if (!prev[key]) return prev
|
||||
const next = { ...prev }
|
||||
delete next[key]
|
||||
return next
|
||||
})
|
||||
}
|
||||
},
|
||||
[clearErrorOnChange],
|
||||
)
|
||||
|
||||
// Validate against the LATEST values via a ref, so handleSubmit stays stable
|
||||
// and never reads a stale snapshot.
|
||||
const valuesRef = useRef(values)
|
||||
valuesRef.current = values
|
||||
const validateRef = useRef(validate)
|
||||
validateRef.current = validate
|
||||
|
||||
const handleSubmit = useCallback(
|
||||
async (e?: { preventDefault?: () => void }) => {
|
||||
e?.preventDefault?.()
|
||||
setErrorMessage(null)
|
||||
|
||||
const errs = validateRef.current ? validateRef.current(valuesRef.current) : {}
|
||||
setErrors(errs)
|
||||
if (Object.keys(errs).length > 0) return
|
||||
|
||||
if (requireTurnstile && !turnstileToken) {
|
||||
setErrorMessage(errorFallback)
|
||||
return
|
||||
}
|
||||
|
||||
setIsSubmitting(true)
|
||||
try {
|
||||
const result = await submitAction(valuesRef.current, turnstileToken ?? undefined)
|
||||
if (result.success) {
|
||||
setIsSuccess(true)
|
||||
setTurnstileToken(null)
|
||||
} else {
|
||||
setErrorMessage(result.message || errorFallback)
|
||||
}
|
||||
} catch (err) {
|
||||
setErrorMessage(err instanceof Error ? err.message : errorFallback)
|
||||
} finally {
|
||||
setIsSubmitting(false)
|
||||
}
|
||||
},
|
||||
[requireTurnstile, turnstileToken, submitAction, errorFallback],
|
||||
)
|
||||
|
||||
const reset = useCallback(() => {
|
||||
setValues(initialRef.current)
|
||||
setErrors({})
|
||||
setIsSuccess(false)
|
||||
setErrorMessage(null)
|
||||
setTurnstileToken(null)
|
||||
}, [])
|
||||
|
||||
return useMemo(
|
||||
() => ({
|
||||
values,
|
||||
errors,
|
||||
isSubmitting,
|
||||
isSuccess,
|
||||
errorMessage,
|
||||
turnstileToken,
|
||||
setField,
|
||||
setValues,
|
||||
setErrors,
|
||||
setTurnstileToken,
|
||||
handleSubmit,
|
||||
reset,
|
||||
}),
|
||||
[
|
||||
values,
|
||||
errors,
|
||||
isSubmitting,
|
||||
isSuccess,
|
||||
errorMessage,
|
||||
turnstileToken,
|
||||
setField,
|
||||
handleSubmit,
|
||||
reset,
|
||||
],
|
||||
)
|
||||
}
|
||||
Reference in New Issue
Block a user