Added form validators
This commit is contained in:
@@ -1,10 +1,15 @@
|
||||
'use client'
|
||||
|
||||
import { useCallback, useState } from 'react'
|
||||
import { useMemo } from 'react'
|
||||
|
||||
import type { SubmitFormResult } from './submitForm.js'
|
||||
import { type FormSubmitAction, useForm } from './useForm.js'
|
||||
import { buildValidator, checked, email, minLength, required } from './validators.js'
|
||||
|
||||
/** Field values the form tracks. Projects add/remove keys freely. */
|
||||
/**
|
||||
* Field values of the STANDARD contact form. This is a preset shape — projects
|
||||
* that need a different field set (or dynamic builder fields) should use
|
||||
* `useForm` directly instead, where the shape is fully open.
|
||||
*/
|
||||
export type ContactFormValues = {
|
||||
consent: boolean
|
||||
email: string
|
||||
@@ -14,22 +19,15 @@ export type ContactFormValues = {
|
||||
topic: string
|
||||
}
|
||||
|
||||
export type ContactFormErrors = Partial<Record<keyof ContactFormValues, boolean>>
|
||||
|
||||
/**
|
||||
* The project's server action that calls submitForm (server-only, holds the
|
||||
* Turnstile secret). The hook is a client hook, so it can't call submitForm
|
||||
* directly — the project injects its action.
|
||||
*/
|
||||
export type SubmitAction = (
|
||||
values: ContactFormValues,
|
||||
turnstileToken?: string,
|
||||
) => Promise<{ message?: string; success: boolean } | SubmitFormResult>
|
||||
export type ContactFormErrors = Partial<Record<keyof ContactFormValues, string>>
|
||||
export type SubmitAction = FormSubmitAction<ContactFormValues>
|
||||
|
||||
type UseContactFormOptions = {
|
||||
/** Generic error message shown when the action throws. */
|
||||
/** Generic error message shown when the action fails/throws. */
|
||||
errorFallback?: string
|
||||
initialTopic?: string
|
||||
/** Override the per-field error message (shown via `errors.<field>`). */
|
||||
messages?: Partial<Record<keyof ContactFormValues, string>>
|
||||
/** Minimum message length. Default 10. */
|
||||
minMessageLength?: number
|
||||
/** Whether consent is required (project passes true when consentText shown). */
|
||||
@@ -41,35 +39,22 @@ type UseContactFormOptions = {
|
||||
submitAction: SubmitAction
|
||||
}
|
||||
|
||||
const EMAIL_RE = /^[^\s@]+@[^\s@][^\s.@]*\.[^\s@]+$/
|
||||
const EMPTY: ContactFormValues = {
|
||||
name: '',
|
||||
consent: false,
|
||||
email: '',
|
||||
message: '',
|
||||
phone: '',
|
||||
topic: '',
|
||||
}
|
||||
|
||||
/**
|
||||
* All contact-form logic (state, validation, Turnstile token, submit, success)
|
||||
* WITHOUT any markup — the project owns 100% of the look. Replaces the ~150
|
||||
* lines of identical logic copied into every project's ContactForm, while the
|
||||
* project keeps full control over field layout and styling.
|
||||
* Zero-config preset over `useForm` for the everyday contact form: standard
|
||||
* fields (name/email/phone/topic/message/consent) and standard rules, wired
|
||||
* for you. Markup and styling stay 100% in the project — this only removes the
|
||||
* duplicated logic.
|
||||
*
|
||||
* const f = useContactForm({ submitAction, requireTurnstile: Boolean(siteKey),
|
||||
* requireTopic: topics.length > 0, requireConsent: Boolean(consentText) })
|
||||
* // in JSX — your own fields/classes:
|
||||
* <input value={f.values.name} onChange={(e) => f.setField('name', e.target.value)}
|
||||
* className={f.errors.name ? 'border-red-500' : '…'} />
|
||||
* <Turnstile siteKey={siteKey} onToken={f.setTurnstileToken} />
|
||||
* <form onSubmit={f.handleSubmit}>…</form>
|
||||
* {f.isSuccess && <YourSuccessPanel onReset={f.reset} />}
|
||||
*
|
||||
* Need custom or dynamic fields? Drop the preset and call `useForm` + validators.
|
||||
*/
|
||||
export function useContactForm(options: UseContactFormOptions) {
|
||||
const {
|
||||
errorFallback = 'Something went wrong. Please try again.',
|
||||
errorFallback,
|
||||
initialTopic = '',
|
||||
messages,
|
||||
minMessageLength = 10,
|
||||
requireConsent = false,
|
||||
requireTopic = false,
|
||||
@@ -77,76 +62,30 @@ export function useContactForm(options: UseContactFormOptions) {
|
||||
submitAction,
|
||||
} = options
|
||||
|
||||
const [values, setValues] = useState<ContactFormValues>({ ...EMPTY, topic: initialTopic })
|
||||
const [errors, setErrors] = useState<ContactFormErrors>({})
|
||||
const [isSubmitting, setIsSubmitting] = useState(false)
|
||||
const [isSuccess, setIsSuccess] = useState(false)
|
||||
const [errorMessage, setErrorMessage] = useState<null | string>(null)
|
||||
const [turnstileToken, setTurnstileToken] = useState<null | string>(null)
|
||||
|
||||
const setField = useCallback(
|
||||
<K extends keyof ContactFormValues>(key: K, value: ContactFormValues[K]) => {
|
||||
setValues((prev) => ({ ...prev, [key]: value }))
|
||||
},
|
||||
[],
|
||||
const validate = useMemo(
|
||||
() =>
|
||||
buildValidator<ContactFormValues>({
|
||||
name: [required(messages?.name)],
|
||||
email: [required(messages?.email), email(messages?.email)],
|
||||
...(requireTopic ? { topic: [required(messages?.topic)] } : {}),
|
||||
message: [required(messages?.message), minLength(minMessageLength, messages?.message)],
|
||||
...(requireConsent ? { consent: [checked(messages?.consent)] } : {}),
|
||||
}),
|
||||
[requireTopic, requireConsent, minMessageLength, messages],
|
||||
)
|
||||
|
||||
const validate = useCallback((): boolean => {
|
||||
const errs: ContactFormErrors = {}
|
||||
if (!values.name.trim()) {errs.name = true}
|
||||
if (!values.email.trim() || !EMAIL_RE.test(values.email)) {errs.email = true}
|
||||
if (requireTopic && !values.topic) {errs.topic = true}
|
||||
if (!values.message.trim() || values.message.length < minMessageLength) {errs.message = true}
|
||||
if (requireConsent && !values.consent) {errs.consent = true}
|
||||
setErrors(errs)
|
||||
return Object.keys(errs).length === 0
|
||||
}, [values, requireTopic, requireConsent, minMessageLength])
|
||||
|
||||
const handleSubmit = useCallback(
|
||||
async (e: { preventDefault: () => void }) => {
|
||||
e.preventDefault()
|
||||
setErrorMessage(null)
|
||||
if (!validate()) {return}
|
||||
if (requireTurnstile && !turnstileToken) {
|
||||
setErrorMessage(errorFallback)
|
||||
return
|
||||
}
|
||||
setIsSubmitting(true)
|
||||
try {
|
||||
const result = await submitAction(values, turnstileToken ?? undefined)
|
||||
if (result.success) {
|
||||
setIsSuccess(true)
|
||||
setTurnstileToken(null)
|
||||
} else {
|
||||
setErrorMessage(('message' in result && result.message) || errorFallback)
|
||||
}
|
||||
} catch (err) {
|
||||
setErrorMessage(err instanceof Error ? err.message : errorFallback)
|
||||
} finally {
|
||||
setIsSubmitting(false)
|
||||
}
|
||||
return useForm<ContactFormValues>({
|
||||
errorFallback,
|
||||
initialValues: {
|
||||
name: '',
|
||||
consent: false,
|
||||
email: '',
|
||||
message: '',
|
||||
phone: '',
|
||||
topic: initialTopic,
|
||||
},
|
||||
[validate, requireTurnstile, turnstileToken, submitAction, values, errorFallback],
|
||||
)
|
||||
|
||||
const reset = useCallback(() => {
|
||||
setValues({ ...EMPTY, topic: initialTopic })
|
||||
setErrors({})
|
||||
setIsSuccess(false)
|
||||
setErrorMessage(null)
|
||||
setTurnstileToken(null)
|
||||
}, [initialTopic])
|
||||
|
||||
return {
|
||||
errorMessage,
|
||||
errors,
|
||||
handleSubmit,
|
||||
isSubmitting,
|
||||
isSuccess,
|
||||
reset,
|
||||
setField,
|
||||
setTurnstileToken,
|
||||
turnstileToken,
|
||||
values,
|
||||
}
|
||||
requireTurnstile,
|
||||
submitAction,
|
||||
validate,
|
||||
})
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user