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.

TypescriptReactForm Validation

Code

snippet
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: react is a real dependency, resolved by the package manager.
  • The guard !fieldRules short-circuits the flow with an early return when 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

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.