Added form validators

This commit is contained in:
2026-10-09 18:23:08 +02:00
parent d500d9412f
commit abf2e7d40f
24 changed files with 738 additions and 255 deletions
+4
View File
@@ -6,5 +6,9 @@ export type { SubmitFormArgs, SubmitFormResult } from './submitForm.js';
export type { FormsCollectionOverrides, FormsFieldsOverride, FormsOption } from './types.js';
export { useContactForm } from './useContactForm.js';
export type { ContactFormErrors, ContactFormValues, SubmitAction } from './useContactForm.js';
export { useForm } from './useForm.js';
export type { FormErrors, FormSubmitAction, Validator } from './useForm.js';
export { validateSubmission } from './validateSubmission.js';
export type { FormValidationResult } from './validateSubmission.js';
export { buildValidator, checked, custom, email, isEmail, maxLength, minLength, pattern, required, } from './validators.js';
export type { Rule } from './validators.js';
+4
View File
@@ -4,6 +4,10 @@ export { buildFormsPlugin } from './formsPluginConfig.js';
export { checkRateLimit } from './rateLimit.js';
export { submitForm } from './submitForm.js';
export { useContactForm } from './useContactForm.js';
// Generic form engine (any field set) + the standard contact-form preset.
export { useForm } from './useForm.js';
export { validateSubmission } from './validateSubmission.js';
// Composable validation rules (pure — safe on server or client).
export { buildValidator, checked, custom, email, isEmail, maxLength, minLength, pattern, required } from './validators.js';
//# sourceMappingURL=index.js.map
+1 -1
View File
@@ -1 +1 @@
{"version":3,"sources":["../../../src/modules/forms/index.ts"],"sourcesContent":["// buildFormsPlugin is config-time (safe anywhere). submitForm is server-only\n// (Turnstile secret) — never import it from a client component.\nexport { buildFormsPlugin } from './formsPluginConfig.js'\nexport { checkRateLimit } from './rateLimit.js'\nexport type { RateLimitArgs } from './rateLimit.js'\nexport { submitForm } from './submitForm.js'\nexport type { SubmitFormArgs, SubmitFormResult } from './submitForm.js'\nexport type { FormsCollectionOverrides, FormsFieldsOverride, FormsOption } from './types.js'\nexport { useContactForm } from './useContactForm.js'\nexport type { ContactFormErrors, ContactFormValues, SubmitAction } from './useContactForm.js'\nexport { validateSubmission } from './validateSubmission.js'\nexport type { FormValidationResult } from './validateSubmission.js'\n"],"names":["buildFormsPlugin","checkRateLimit","submitForm","useContactForm","validateSubmission"],"mappings":"AAAA,6EAA6E;AAC7E,gEAAgE;AAChE,SAASA,gBAAgB,QAAQ,yBAAwB;AACzD,SAASC,cAAc,QAAQ,iBAAgB;AAE/C,SAASC,UAAU,QAAQ,kBAAiB;AAG5C,SAASC,cAAc,QAAQ,sBAAqB;AAEpD,SAASC,kBAAkB,QAAQ,0BAAyB"}
{"version":3,"sources":["../../../src/modules/forms/index.ts"],"sourcesContent":["// buildFormsPlugin is config-time (safe anywhere). submitForm is server-only\n// (Turnstile secret) — never import it from a client component.\nexport { buildFormsPlugin } from './formsPluginConfig.js'\nexport { checkRateLimit } from './rateLimit.js'\nexport type { RateLimitArgs } from './rateLimit.js'\nexport { submitForm } from './submitForm.js'\nexport type { SubmitFormArgs, SubmitFormResult } from './submitForm.js'\nexport type { FormsCollectionOverrides, FormsFieldsOverride, FormsOption } from './types.js'\nexport { useContactForm } from './useContactForm.js'\nexport type { ContactFormErrors, ContactFormValues, SubmitAction } from './useContactForm.js'\n// Generic form engine (any field set) + the standard contact-form preset.\nexport { useForm } from './useForm.js'\nexport type { FormErrors, FormSubmitAction, Validator } from './useForm.js'\nexport { validateSubmission } from './validateSubmission.js'\nexport type { FormValidationResult } from './validateSubmission.js'\n// Composable validation rules (pure — safe on server or client).\nexport {\n buildValidator,\n checked,\n custom,\n email,\n isEmail,\n maxLength,\n minLength,\n pattern,\n required,\n} from './validators.js'\nexport type { Rule } from './validators.js'\n"],"names":["buildFormsPlugin","checkRateLimit","submitForm","useContactForm","useForm","validateSubmission","buildValidator","checked","custom","email","isEmail","maxLength","minLength","pattern","required"],"mappings":"AAAA,6EAA6E;AAC7E,gEAAgE;AAChE,SAASA,gBAAgB,QAAQ,yBAAwB;AACzD,SAASC,cAAc,QAAQ,iBAAgB;AAE/C,SAASC,UAAU,QAAQ,kBAAiB;AAG5C,SAASC,cAAc,QAAQ,sBAAqB;AAEpD,0EAA0E;AAC1E,SAASC,OAAO,QAAQ,eAAc;AAEtC,SAASC,kBAAkB,QAAQ,0BAAyB;AAE5D,iEAAiE;AACjE,SACEC,cAAc,EACdC,OAAO,EACPC,MAAM,EACNC,KAAK,EACLC,OAAO,EACPC,SAAS,EACTC,SAAS,EACTC,OAAO,EACPC,QAAQ,QACH,kBAAiB"}
+28 -32
View File
@@ -1,5 +1,9 @@
import type { SubmitFormResult } from './submitForm.js';
/** Field values the form tracks. Projects add/remove keys freely. */
import { type FormSubmitAction } from './useForm.js';
/**
* 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;
@@ -8,20 +12,14 @@ export type ContactFormValues = {
phone: string;
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). */
@@ -33,32 +31,30 @@ type UseContactFormOptions = {
submitAction: SubmitAction;
};
/**
* 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 declare function useContactForm(options: UseContactFormOptions): {
errorMessage: string | null;
errors: Partial<Record<keyof ContactFormValues, boolean>>;
handleSubmit: (e: {
preventDefault: () => void;
}) => Promise<void>;
values: ContactFormValues;
errors: Partial<Record<keyof ContactFormValues, string>>;
isSubmitting: boolean;
isSuccess: boolean;
reset: () => void;
setField: <K extends keyof ContactFormValues>(key: K, value: ContactFormValues[K]) => void;
setTurnstileToken: import("react").Dispatch<import("react").SetStateAction<string | null>>;
errorMessage: string | null;
turnstileToken: string | null;
values: ContactFormValues;
setField: <K extends keyof ContactFormValues>(key: K, value: ContactFormValues[K]) => void;
setValues: import("react").Dispatch<import("react").SetStateAction<ContactFormValues>>;
setErrors: import("react").Dispatch<import("react").SetStateAction<Partial<Record<keyof ContactFormValues, string>>>>;
setTurnstileToken: import("react").Dispatch<import("react").SetStateAction<string | null>>;
handleSubmit: (e?: {
preventDefault?: (() => void) | undefined;
} | undefined) => Promise<void>;
reset: () => void;
};
export {};
+48 -113
View File
@@ -1,126 +1,61 @@
'use client';
import { useCallback, useState } from 'react';
const EMAIL_RE = /^[^\s@]+@[^\s@][^\s.@]*\.[^\s@]+$/;
const EMPTY = {
name: '',
consent: false,
email: '',
message: '',
phone: '',
topic: ''
};
import { useMemo } from 'react';
import { useForm } from './useForm.js';
import { buildValidator, checked, email, minLength, required } from './validators.js';
/**
* 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) {
const { errorFallback = 'Something went wrong. Please try again.', initialTopic = '', minMessageLength = 10, requireConsent = false, requireTopic = false, requireTurnstile = false, submitAction } = options;
const [values, setValues] = useState({
...EMPTY,
topic: initialTopic
});
const [errors, setErrors] = useState({});
const [isSubmitting, setIsSubmitting] = useState(false);
const [isSuccess, setIsSuccess] = useState(false);
const [errorMessage, setErrorMessage] = useState(null);
const [turnstileToken, setTurnstileToken] = useState(null);
const setField = useCallback((key, value)=>{
setValues((prev)=>({
...prev,
[key]: value
}));
}, []);
const validate = useCallback(()=>{
const errs = {};
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,
const { errorFallback, initialTopic = '', messages, minMessageLength = 10, requireConsent = false, requireTopic = false, requireTurnstile = false, submitAction } = options;
const validate = useMemo(()=>buildValidator({
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
minMessageLength,
messages
]);
const handleSubmit = useCallback(async (e)=>{
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);
}
}, [
validate,
requireTurnstile,
turnstileToken,
submitAction,
values,
errorFallback
]);
const reset = useCallback(()=>{
setValues({
...EMPTY,
return useForm({
errorFallback,
initialValues: {
name: '',
consent: false,
email: '',
message: '',
phone: '',
topic: initialTopic
});
setErrors({});
setIsSuccess(false);
setErrorMessage(null);
setTurnstileToken(null);
}, [
initialTopic
]);
return {
errorMessage,
errors,
handleSubmit,
isSubmitting,
isSuccess,
reset,
setField,
setTurnstileToken,
turnstileToken,
values
};
},
requireTurnstile,
submitAction,
validate
});
}
//# sourceMappingURL=useContactForm.js.map
File diff suppressed because one or more lines are too long
+70
View File
@@ -0,0 +1,70 @@
/**
* 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 declare function useForm<T extends Record<string, unknown>>(options: UseFormOptions<T>): {
values: T;
errors: Partial<Record<keyof T, string>>;
isSubmitting: boolean;
isSuccess: boolean;
errorMessage: string | null;
turnstileToken: string | null;
setField: <K extends keyof T>(key: K, value: T[K]) => void;
setValues: import("react").Dispatch<import("react").SetStateAction<T>>;
setErrors: import("react").Dispatch<import("react").SetStateAction<Partial<Record<keyof T, string>>>>;
setTurnstileToken: import("react").Dispatch<import("react").SetStateAction<string | null>>;
handleSubmit: (e?: {
preventDefault?: () => void;
}) => Promise<void>;
reset: () => void;
};
export {};
+122
View File
@@ -0,0 +1,122 @@
'use client';
import { useState, useCallback, useRef, useMemo } from 'react';
/**
* 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(options) {
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(initialRef.current);
const [errors, setErrors] = useState({});
const [isSubmitting, setIsSubmitting] = useState(false);
const [isSuccess, setIsSuccess] = useState(false);
const [errorMessage, setErrorMessage] = useState(null);
const [turnstileToken, setTurnstileToken] = useState(null);
const setField = useCallback((key, value)=>{
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)=>{
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
]);
}
//# sourceMappingURL=useForm.js.map
File diff suppressed because one or more lines are too long
+43
View File
@@ -0,0 +1,43 @@
import type { Validator } from './useForm.js';
/**
* Composable validation rules + a builder that turns a per-field schema into a
* `Validator<T>`. These are the bits that actually repeat across projects
* (required / email / min-length / checkbox-must-be-true); the field SET and
* the MARKUP stay in the project.
*
* Pure functions, no 'use client' — usable both in the client `useForm` hook
* and server-side (e.g. re-validating inside a server action).
*
* const validate = buildValidator<MyValues>({
* email: [required(), email()],
* message: [required(), minLength(10)],
* consent: [checked()],
* })
*
* Dynamic / builder-driven forms build the schema at runtime:
*
* const schema = Object.fromEntries(
* fields.map((f) => [f.name, f.required ? [required()] : []]),
* )
* const validate = buildValidator(schema)
*/
/** A rule returns `true` when the value is OK, or an error message string. */
export type Rule = (value: unknown, values: Record<string, unknown>) => true | string;
/** Standalone e-mail check, handy outside the rule system too. */
export declare const isEmail: (v: unknown) => boolean;
/** Non-empty string, non-null, and (for checkboxes) not `false`. */
export declare const required: (msg?: string) => Rule;
export declare const email: (msg?: string) => Rule;
export declare const minLength: (n: number, msg?: string) => Rule;
export declare const maxLength: (n: number, msg?: string) => Rule;
/** Checkbox must be ticked (true). */
export declare const checked: (msg?: string) => Rule;
/** Value must match a regex (ignored when empty — pair with `required` to force). */
export declare const pattern: (re: RegExp, msg?: string) => Rule;
/** Escape hatch: any predicate → rule. */
export declare const custom: (test: (value: unknown, values: Record<string, unknown>) => boolean, msg: string) => Rule;
/**
* Compose a `Validator<T>` from per-field rule lists. First failing rule for a
* field wins. Fields with no rules (or an empty list) are skipped.
*/
export declare function buildValidator<T extends Record<string, unknown>>(schema: Partial<Record<keyof T, Rule[]>>): Validator<T>;
+37
View File
@@ -0,0 +1,37 @@
const EMAIL_RE = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
/** Standalone e-mail check, handy outside the rule system too. */ export const isEmail = (v)=>typeof v === 'string' && EMAIL_RE.test(v.trim());
/** Non-empty string, non-null, and (for checkboxes) not `false`. */ export const required = (msg = 'required')=>(v)=>{
if (v == null) return msg;
if (typeof v === 'string' && !v.trim()) return msg;
if (v === false) return msg;
return true;
};
export const email = (msg = 'invalid email')=>(v)=>isEmail(v) ? true : msg;
export const minLength = (n, msg)=>(v)=>typeof v === 'string' && v.trim().length >= n ? true : msg ?? `min ${n} chars`;
export const maxLength = (n, msg)=>(v)=>typeof v === 'string' && v.trim().length <= n ? true : msg ?? `max ${n} chars`;
/** Checkbox must be ticked (true). */ export const checked = (msg = 'required')=>(v)=>v === true ? true : msg;
/** Value must match a regex (ignored when empty — pair with `required` to force). */ export const pattern = (re, msg = 'invalid format')=>(v)=>typeof v !== 'string' || v.trim() === '' || re.test(v.trim()) ? true : msg;
/** Escape hatch: any predicate → rule. */ export const custom = (test, msg)=>(v, values)=>test(v, values) ? true : msg;
/**
* Compose a `Validator<T>` from per-field rule lists. First failing rule for a
* field wins. Fields with no rules (or an empty list) are skipped.
*/ export function buildValidator(schema) {
return (values)=>{
const errs = {};
const all = values;
for(const key in schema){
const rules = schema[key];
if (!rules || rules.length === 0) continue;
for (const rule of rules){
const res = rule(all[key], all);
if (res !== true) {
errs[key] = res;
break;
}
}
}
return errs;
};
}
//# sourceMappingURL=validators.js.map
File diff suppressed because one or more lines are too long