React Form Validation with Custom Hook
Validate React form fields using a custom useForm hook with real-time error messages, submission blocking, and TypeScript type safety for form data and.
Code
import { useState, useCallback } from 'react';
interface ValidationRule {
required?: boolean;
minLength?: number;
pattern?: RegExp;
message: string;
}
export function useForm<T extends Record<string, string>>(
initialValues: T,
rules: Partial<Record<keyof T, ValidationRule[]>>,
) {
const [values, setValues] = useState(initialValues);
const [errors, setErrors] = useState<Partial<Record<keyof T, string>>>({});
const validate = useCallback(
(name: keyof T, value: string) => {
const fieldRules = rules[name];
if (!fieldRules) return '';
for (const rule of fieldRules) {
if (rule.required && !value) return rule.message;
if (rule.minLength && value.length < rule.minLength) return rule.message;
if (rule.pattern && !rule.pattern.test(value)) return rule.message;
}
return '';
},
[rules],
);
const handleChange = (name: keyof T, value: string) => {
setValues((prev) => ({ ...prev, [name]: value }));
setErrors((prev) => ({ ...prev, [name]: validate(name, value) }));
};
const isValid = Object.keys(rules).every((key) => !validate(key as keyof T, values[key as keyof T]));
return { values, errors, handleChange, isValid };
}How it works
Count the function handleChange as the entire surface area of React Form Validation with Custom Hook.
The cycling part of this snippet is for (const rule of fieldRules). From react it pulls useState, useCallback — the imports name exactly which library surface the snippet touches.
The result comes back as an object carrying values, errors, handleChange.
Watch out for
- Plan for an install step:
reactis a real dependency, resolved by the package manager. - The guard
!fieldRulesshort-circuits the flow with an earlyreturnwhen its condition holds.
Using it
Callers only need useForm — everything else stays internal.
The call returns values, errors, handleChange — destructure what you need at the call site.
Key statements
const isValid = Object.keys(rules).every((key) => !validate(key as keyof T, values[key as keyof T]));
const handleChange = (name: keyof T, value: string) => {
setValues((prev) => ({ ...prev, [name]: value }));
setErrors((prev) => ({ ...prev, [name]: validate(name, value) }));
};
if (rule.minLength && value.length < rule.minLength) return rule.message;
Interactive Tools for This Topic
JSON to Zod Schema ConverterInfer typed Zod z.object schemas from JSON payloads locally, supporting nested objects, merged array shapes, enums, nullable fields, and JSDoc comments.JSON Schema ValidatorValidate JSON data against a JSON Schema definition and get detailed error reports. Supports type checking, required fields, and common constraint validation.JSONL / NDJSON InspectorValidate NDJSON and JSON Lines line-by-line, pinpoint syntax errors by line number, analyze key frequencies and types, and export a pretty JSON array.Credit Card Brand DetectorIdentify the card network from a number's prefix and length, validate the Luhn checksum, and show a masked form and the issuer identification number.
FAQ
- Does `useForm` modify its input?
- It does not. Inputs are only read; the return value is freshly built.
- Does this require external packages?
- Yes — `react`. Add it to your project before running the snippet.
Report a problem with this exampleOpens a pre-filled issue on GitHub.