Overview
TheuseFormEngine hook provides a complete form management solution with built-in validation. It handles form state, field-level validation, and change events while automatically compiling validation rules from your form schema.
Import
Type Signature
Parameters
Array of field configuration objects. Each field must include:
id(string): Unique identifier for the fieldfieldValidators(FieldValidatorType[]): Array of validation rules
{ type: "required" }- Field must have a value{ type: "minLength", constraints: { minLength: number } }- Minimum character length{ type: "maxLength", constraints: { minLength: number } }- Maximum character length
Return Value
Object containing current values for all form fields, keyed by field ID.
Change handler function that updates field values and triggers validation.Parameters:
e: React change event from the input elementfieldId: The unique identifier of the field being updated
Object containing validation error messages for fields that failed validation, keyed by field ID. Empty string indicates no error.
Usage Example
How It Works
-
Schema Compilation: On initialization, the hook compiles the form schema by attaching validator functions to each field using
attachValidators -
State Management: Maintains two state objects:
formData: Stores current field valueserrors: Stores validation error messages
-
Validation Flow: When a field changes:
- Updates the field value in
formData - Retrieves the compiled field schema
- Runs all validators for that field sequentially
- Stops at the first validation error
- Updates the
errorsstate with the result
- Updates the field value in
- Real-time Feedback: Validation runs on every change, providing immediate feedback to users
Related Types
Source
Implemented in:src/app/hooks/useFormEngine.tsx:9