Form Validation
React-Forminate
provides a robust validation system with multiple validation strategies, customizable error messages, and flexible validation triggers. This guide covers all aspects of form validation in the library.
Validation Basics
Required Fields
Mark a field as required and customize its error message:
Required Fields Form
This code example demonstrates Demonstrates required field validation in React-Forminate with custom error messages for form fields. in React-Forminate.
Key features shown: Required field validation, Custom error messages, Form submission handling, Type-safe form schema, Console logging for debugging
1
2import { DynamicForm, type FormDataCollectionType } from "react-forminate";3
4// ... [collapsed start code] ...5
6 {7 fieldId: "username",8 type: "text",9 label: "Username",10 required: true,11 requiredMessage: "Username is mandatory", // Custom message12 },13 // 14// ... [collapsed end code] ...15};16
17
Validation Triggers
Control when validation occurs:
const formData = {
formId: "myForm",
options: {
validateFieldsOnBlur: true // Default (true = validate on blur, false = validate on change)
},
fields: [
// your fields
]
}
Validation Types
Pattern Matching
Validate against regular expressions:
Pattern Matching Form
This code example demonstrates Demonstrates regex pattern validation in React-Forminate with username format enforcement (5-20 alphanumeric chars). in React-Forminate.
Key features shown: Regex pattern validation, Custom validation messages, Pre-filled invalid default value, Real-time validation feedback, Form submission handling
1
2import { DynamicForm, type FormDataCollectionType } from "react-forminate";3
4// ... [collapsed start code] ...5
6 {7 fieldId: "username",8 type: "text",9 label: "Username",10 validation: [11 {12 pattern: "^[a-zA-Z0-9_]{5,20}$",13 message: "5-20 chars: letters, numbers, or underscores only.",14 },15 ],16 _defaultValue: "test" //validation fails17 },18 // 19// ... [collapsed end code] ...20};21
22
Length Validation
For text fields:
Length Validation Form
This code example demonstrates Demonstrates min/max length validation for textarea fields in React-Forminate with character count enforcement (10-200 chars). in React-Forminate.
Key features shown: Textarea length validation, Min/max character enforcement, Custom validation messages, Placeholder guidance, Required field validation, Form submission handling
1
2import { DynamicForm, type FormDataCollectionType } from "react-forminate";3
4// ... [collapsed start code] ...5
6 {7 fieldId: "bio",8 type: "textarea",9 label: "Biography",10 minLength: 10,11 maxLength: 200,12 required: true,13 validation: [14 {15 minLength: 10,16 maxLength: 200,17 message: "Bio's length must be between 10 to 200 characters"18 }19 ],20 placeholder: "Tell us about yourself (10-200 chars)"21 }22 // 23// ... [collapsed end code] ...24};25
26
Numeric Validation
For number fields:
Numeric Validation Form
This code example demonstrates Demonstrates numeric range validation (18-100) for age input fields in React-Forminate with min/max value enforcement. in React-Forminate.
Key features shown: Numeric range validation, Min/max value enforcement, Age input validation, Custom validation messages, Required field handling, Form submission logging
1
2import { DynamicForm, type FormDataCollectionType } from "react-forminate";3
4// ... [collapsed start code] ...5
6 {7 fieldId: "age",8 type: "number",9 label: "Age",10 required: true,11 validation: [12 {13 min: 18,14 max: 100,15 message: "Must be between 18 to 100",16 },17 ],18 placeholder: "How old are you?",19 },20 // 21// ... [collapsed end code] ...22};23
24
OR
validation: [
{
min: 18,
message: "Must be at least 18"
},
{
max: 100,
message: "Cannot exceed 100"
},
]
Date Validation
For date fields:
Date Validation Form
This code example demonstrates Demonstrates date range validation in React-Forminate with min/max date enforcement (January 1, 2025 - December 31, 2026) for arrival date selection. in React-Forminate.
Key features shown: Date range validation, Min/max date enforcement, Arrival date picker, Custom validation messages, Required field handling, Form submission logging
1
2import { DynamicForm, type FormDataCollectionType } from "react-forminate";3
4// ... [collapsed start code] ...5
6 {7 fieldId: "arrivalDate",8 type: "date",9 label: "Arrival Date",10 required: true,11 validation: [12 {13 minDate: "2025-01-01",14 maxDate: "2026-12-31",15 message: "Must be after January 1, 2000 and before 2024",16 },17 ],18 },19 // 20// ... [collapsed end code] ...21};22
23
OR
validation: [
{
minDate: "2025-01-01",
message: "Must be after January 1, 2025"
},
{
maxDate: "2026-12-31",
message: "Must be before 2026"
}
]
Array Validation
For checkbox groups and multi-selects:
Array Field Validation
This code example demonstrates Demonstrates checkbox group validation in React-Forminate with minimum (1) and maximum (3) selection requirements for language options. in React-Forminate.
Key features shown: Checkbox group validation, Minimum selection requirement (1), Maximum selection limit (3), Multi-language options, Custom validation messages, Required field handling
1
2import { DynamicForm, type FormDataCollectionType } from "react-forminate";3
4// ... [collapsed start code] ...5
6 validation: [7 {8 minItems: 1,9 message: "Select at least one option",10 },11 {12 maxItems: 3,13 message: "Select no more than three options",14 },15 ],16 // 17// ... [collapsed end code] ...18};19
20
Custom Validation
Implement complex validation logic:
Custom Validation Form
This code example demonstrates Demonstrates custom validation logic in React-Forminate with uppercase enforcement for currency code inputs, including a valid default value example. in React-Forminate.
Key features shown: Custom validation function, Uppercase enforcement, Currency code validation, Default value demonstration, Real-time validation feedback, Form submission handling
1
2import { DynamicForm, type FormDataCollectionType } from "react-forminate";3
4// ... [collapsed start code] ...5
6 {7 fieldId: "currencyCode",8 type: "text",9 label: "Currency code",10 required: true,11 validation: [12 {13 custom: (value) => {14 // Must be all uppercase15 return value === (value as string).toUpperCase();16 },17 message: "Must be uppercase only",18 },19 ],20 _defaultValue: "USD", //valid input21 },22 // 23// ... [collapsed end code] ...24};25
26
Validation Strategies
React-Forminate
uses a strategy pattern for validation. Here are all built-in strategies:
Strategy | Applies To | Description |
---|---|---|
pattern | Text fields | Regex pattern matching |
minLength | Text fields | Minimum character length |
maxLength | Text fields | Maximum character length |
min | Number fields | Minimum numeric value |
max | Number fields | Maximum numeric value |
minDate | Date fields | Earliest allowed date |
maxDate | Date fields | Latest allowed date |
minItems | Array fields | Minimum selected items |
maxItems | Array fields | Maximum selected items |
required | All fields | Field is mandatory |
custom | All fields | Custom validation function |
Advanced Validation
Conditional Validation
Show/hide fields based on other field values, and if the field is not visible, the validation engine automatically does not check that field:
Conditional Validation Form
This code example demonstrates Demonstrates conditional field visibility in React-Forminate, showing spouse name field only when 'married' is selected, with dynamic required validation. in React-Forminate.
Key features shown: Conditional field visibility, Radio button dependencies, Dynamic required validation, Form field relationships, Real-time form adaptation, Clean state management
1
2import { DynamicForm, type FormDataCollectionType } from "react-forminate";3
4// ... [collapsed start code] ...5
6 {7 fieldId: "spouseName",8 type: "text",9 label: "Spouse Name",10 visibility: {11 dependsOn: "maritalStatus", //Id of the dependant field12 condition: "equals",13 value: "yes",14 },15 required: true,16 },17 // 18// ... [collapsed end code] ...19};20
21
Custom Validation Strategies
Register custom validation strategies to be able to use them in all forms globally and doesn't need to define custom validation per forms:
Validation Form Custom Strategies
This code example demonstrates Demonstrates custom IBAN validation strategy in React-Forminate, showing how to create and register reusable validation logic for international bank account numbers. in React-Forminate.
Key features shown: Custom validation strategy, IBAN format validation, Global strategy registration, Regex pattern validation, Reusable validation logic, Form integration example
1import {2 DynamicForm,3 validationEngine,4 ValidationResponseType,5 type FormDataCollectionType,6} from "react-forminate";7
8//Define a validation custom strategy9class IbanValidationStrategy {10 validate(value: string): ValidationResponseType {11 // Simple IBAN regex validation (basic format check)12 const ibanRegex = /^[A-Z]{2}d{16}[A-Z0-9]{1,30}$/;13
14 const isFormatValid = ibanRegex.test(value);15
16 return {17 isValid: isFormatValid,18 message: isFormatValid ? "" : "Invalid IBAN format",19 };20 }21}22const SampleFormWithCustomStrategy = () => {23 const formSchema: FormDataCollectionType = {24 formId: "validationForm_custom_strategies",25 title: "Validation Form Custom Strategies",26 fields: [27 {28 fieldId: "iban",29 type: "text",30 label: "IBAN",31 required: true,32 placeholder: "Enter your International Bank Account Number",33 description:34 "A sample valid value to be tested for IBAN field: IR12345678900000001",35 validation: [36 {37 type: "IBAN", //uses of the custom validation strategies38 },39 ],40 },41 ],42 };43 const handleSubmit = (values: any, isValid: boolean) => {44 console.log("Form Data:", values, "Is Valid:", isValid);45 };46 return <DynamicForm formData={formSchema} onSubmit={handleSubmit} />;47};48
49const App = () => {50 validationEngine.registerStrategy("IBAN", new IbanValidationStrategy());51
52 return <SampleFormWithCustomStrategy />;53};54
Error Handling
Accessing Errors
Errors are available through the useFormErrors
hook:
const formErrors = useFormErrors("formId"); //Instead of the formId you must put your form's Id
Displaying Errors
Errors are automatically displayed below each field, but you can customize:
By wrapping the app by using of the provider <FormRegistryProvider>{children}</FormRegistryProvider>
you can access to the various numbers of custom hooks that the React-Forminate provides you, and by using of the useFormErrors()
you can get the form's validation errors.
You can see the usage of the provider and the relevant hook in the below example:
Validation Form Errors
This code example demonstrates Demonstrates custom error handling in React-Forminate using FormRegistryProvider and useFormErrors hook, with manual error display for form validation messages. in React-Forminate.
Key features shown: Custom error display, FormRegistryProvider usage, useFormErrors hook, Manual error rendering, Multi-field validation, Email format validation, Required field handling
1
2import {3 DynamicForm,4// ... [collapsed start code] ...5
6 const errors = useFormErrors("validationForm_errors"); //The hook takes the form ID7 8// ... [collapsed end code] ...9};10
11
Manual Form Validation Control
React-Forminate provides powerful hooks for granular form control, allowing you to trigger validation precisely when needed. This is particularly useful for custom submission flows or when you need to validate without immediate user interaction.
Key Features Demonstrated:
- Manual Validation Trigger - Validate the entire form programmatically
- Form State Access - Retrieve current form values and validation status
- Custom Submission Handling - Implement your own submission logic
Implementation Example:
Manually Trigger Form Validation
This code example demonstrates Demonstrates manual form validation triggering in React-Forminate using useFormActions and useFormValues hooks, with custom submit button and validation state handling. in React-Forminate.
Key features shown: Manual validation triggering, useFormActions hook, useFormValues hook, Custom submit button, Programmatic validation, Form state access, Async validation handling
1
2import {3 DynamicForm,4// ... [collapsed start code] ...5
6 const values = useFormValues("validationForm_manual_validate");7 const { validateForm } = useFormActions("validationForm_manual_validate");8 9// ... [collapsed end code] ...10};11
12
When to Use Manual Validation:
- Custom submission workflows (e.g., multi-step forms)
- Conditional validation (validate only when certain criteria are met)
- Asynchronous validation (after API checks or complex calculations)
- UI/UX requirements (delayed validation feedback)
Benefits:
- Full control over validation timing
- Access to validation results before submission
- Ability to mix manual and automatic validation
- Clean separation of validation and submission logic
The example shows how to combine useFormValues
and useFormActions
to create a flexible validation flow while maintaining access to all form state.
Complete Example
Manually Trigger Form Validation
This code example demonstrates Complete user registration form example with email validation, password field, age verification, and newsletter subscription using React-Forminate's validation system. in React-Forminate.
Key features shown: Email format validation, Password field with validation, Age verification (18-120), Newsletter subscription toggle, Blur-based validation, Multi-field form handling, Form submission logging
1
2import { DynamicForm, type FormDataCollectionType } from "react-forminate";3
4// ... [collapsed start code] ...5
6 fields: [7 {8 fieldId: "email",9 type: "email",10 label: "Email",11 required: true,12 validation: [13 {14 pattern: "^\S+@\S+\.\S+$",15 message: "Enter a valid email address",16 },17 ],18 },19 {20 fieldId: "password",21 type: "password",22 label: "Password",23 required: true,24 validation: [25 {26 type: "password",27 },28 ],29 },30 {31 fieldId: "age",32 type: "number",33 label: "Age",34 required: true,35 validation: [36 {37 min: 18,38 message: "You must be 18 or older",39 },40 {41 max: 120,42 message: "Enter a realistic age",43 },44 ],45 },46 {47 fieldId: "subscribe",48 type: "checkbox",49 required: true,50 itemsClassName: "text-gray-100",51 options: [52 {53 value: "yes",54 label: "Subscribe the newsletter",55 },56 ],57 },58 ],59 60// ... [collapsed end code] ...61};62
63