Download the PHP package coroq/form without Composer
On this page you can find all versions of the php package coroq/form. It is possible to download/install these versions without Composer. Possible dependencies are resolved automatically.
Package form
Short Description Type-safe PHP form validation library with filtering, nested forms, and typed error objects. Zero dependencies.
License MIT
Informations about the package form
Coroq Form
PHP form validation library. Type-safe, zero dependencies.
Scope
What This Library Does
- Value validation and filtering - Validates and normalizes form input (email, URL, numbers, dates, text, etc.)
- Type-safe form handling - Provides typed input classes with IDE autocomplete support
- Error management - Tracks validation errors as typed objects (not string codes)
- Nested forms - Supports hierarchical form structures (forms within forms)
- Dynamic lists - Manages repeating form items (e.g., multiple email addresses)
- Cross-field validation - Validates relationships between fields (e.g., password confirmation)
What This Library Does NOT Do
- HTML rendering - This library does not generate HTML. You write your own templates.
- HTTP request handling - Does not parse
$_POSTor$_FILES. You pass data tosetValue(). - CSRF protection - Does not generate or validate CSRF tokens. Use your framework's CSRF protection.
- Database operations - Does not save or load data from databases. Use your ORM/database layer.
- Framework integration - Framework-agnostic. Integrate it yourself or use it standalone.
- Client-side validation - Server-side only. Add your own JavaScript validation if needed.
This is a validation and data processing layer that sits between your HTTP layer and business logic.
Requirements
- PHP >= 8.0
- mbstring extension
- fileinfo extension
- filter extension
- bcmath extension
- intl extension (optional)
Installation
Quick Start
Core Concepts
1. Forms and Form Items
A Form holds items with names. Each item represents a single field - an email address, a username, a number, etc.
2. Setting Values
When you assign values to a form, the form distributes those values to its items by matching names. Each item receives and stores its corresponding value.
3. Filtering
The moment a value is set, it is automatically filtered - normalized and transformed according to the item's type. Email addresses get trimmed and lowercased, numbers get stripped of formatting.
4. Validation and Errors
When you request validation, the form checks all its items. Each item validates its value against its rules. The form returns whether all items are valid. Invalid items store an error object representing what went wrong.
Defining Forms
Recommended: Form Subclasses
Define form classes with typed readonly properties for IDE support:
Dynamic Forms (for temporal use)
For dynamic or one-off forms, you can use Form directly:
Form State
Form items have three state flags that control their behavior:
Required/Optional
Input level:
setRequired(true)(default) - Empty value fails validation with EmptyErrorsetRequired(false)- Empty value passes validation
Form level:
setRequired(true)(default) - Validates all enabled items even if form is emptysetRequired(false)- If the entire form is empty, validation passes without checking items
Form-level example:
Read-Only
Input level:
setValue()is ignored (value doesn't change)- Item is included in
getValue()andvalidate()
Form level:
setValue()is ignored for the entire form- Items are included in
getValue()andvalidate()
Form-level example:
Disabled
Disabled items are excluded from output and validation, but still accept values.
Item behavior when disabled:
getValue()returns the item's empty value (see each class for definition)isEmpty()returnstruesetValue()accepts and stores the valuevalidate()is skipped
Parent form behavior:
- Disabled child items are excluded from parent's
getValue()andvalidate() - Useful for conditionally hiding entire form sections
Form-level example:
State Summary
| State | setValue() | getValue() | validate() |
|---|---|---|---|
| Normal (required=true) | ✓ Sets value | ✓ Returns value | ✓ Validated, must not be empty |
| Optional (required=false) | ✓ Sets value | ✓ Returns value | ✓ Validated, empty allowed |
| Read-only | ✗ Ignored | ✓ Returns value | ✓ Validated |
| Disabled | ✓ Sets value | Returns empty value | ✗ Skipped |
Form-level states apply to the form as a whole:
- Required=false on Form: Empty form passes validation
- ReadOnly on Form: setValue() ignored for entire form
- Disabled on Form: Returns empty value; excluded from parent's getValue/validate
Validation
Custom Validators
All Input subclasses support custom validators via setValidator(). This allows you to add validation logic without creating custom subclasses.
Basic Example
How It Works
The validator:
- Receives two parameters:
$formItem(the input itself) and$value(the filtered value) - Runs after the input's built-in validation (
doValidate()) passes - Returns an
Errorobject if validation fails, ornullif valid - Does not run if the value is empty or if built-in validation fails
Advanced Examples
Accessing form item properties:
External Validation
When you validate a value in external logic (authentication, API calls, business rules) but want to hold the error in the form, use setError() on a form item. The form item can be used only for holding the error.
Conditional Validation
Make validation rules conditional based on other field values by overriding setValue() in your Form subclass.
This pattern works for any conditional logic: disabling fields, changing constraints, or toggling entire sections.
For conditional sections (multi-step forms, draft/publish workflows), use nested forms with setDisabled():
Error Handling
Error Customizer
Transform error objects before they are stored. Useful for converting generic errors to field-specific error types.
The customizer receives $error and $formItem, runs after validation, and returns the transformed error. You can replace the error object or mutate it by adding properties.
Error Messages
Use ErrorMessageFormatter to convert error objects to human-readable messages. You define your own message set by mapping error class names to messages (strings or closures).
Basic Usage
Error Hierarchy and Inheritance
The formatter uses instanceof matching, supporting error class inheritance. Many specific errors extend base error types. For example, InvalidEmailError, InvalidUrlError, InvalidDateError, InvalidMimeTypeError, and InvalidExtensionError all extend InvalidError.
Define base messages as defaults, then override specific types as needed:
Later definitions override earlier ones. This makes it easy to merge preset messages with custom overrides:
Adding Individual Messages
Use setMessage() to add or override individual messages without replacing the entire set:
Dynamic Messages with Closures
Use closures to access error object properties for dynamic messages:
Custom Error Types
You can create custom error classes for application-specific validation:
Built-in Error Types
The library provides these error types:
Base Errors:
EmptyError- Required field is emptyInvalidError- Generic validation failure (base class for format validation errors)
*Invalid Hierarchy (all extend InvalidError):**
InvalidEmailError- Invalid email formatInvalidUrlError- Invalid URL formatInvalidDateError- Invalid date formatInvalidMimeTypeError- File MIME type not allowedInvalidExtensionError- File extension not allowed
Range/Length Errors:
TooShortError,TooLongError- String length validationTooSmallError,TooLargeError- Number range validationTooFewSelectionsError,TooManySelectionsError- Multi-select count
Type/Format Errors:
NotIntegerError,NotNumericError- Type validationPatternMismatchError- Pattern validation failure
Selection Errors:
NotInOptionsError- Invalid selection value
File Errors:
FileNotFoundError- File not found at pathFileTooLargeError,FileTooSmallError- File size range
Derived Errors:
SourceItemInvalidError- Derived item's source failed validation
Tip: Define messages for base error types (like InvalidError) as catch-alls, then optionally override specific subtypes for custom messages.
Form Values
Forms provide four methods to retrieve values:
getValue()- All values as strings (includes empty values)getFilledValue()- Only non-empty values as stringsgetParsedValue()- Values with proper types, ornullif empty/invalidgetFilledParsedValue()- Only non-empty values with proper types
getParsedValue() Contract
getParsedValue() returns null if the value is empty or invalid, otherwise returns the value converted to its appropriate type.
This applies to all form items:
- Empty values always return
null(not empty strings) - Invalid values return
null(e.g., malformed email, out-of-range integer) - Valid values return the appropriate PHP type (int, float, bool, DateTime, string, array)
Special cases:
BooleanInput::getParsedValue()always returnsbool(nevernull) - unchecked =false, checked =trueMultiSelect::getParsedValue()always returnsarray(nevernull) - empty selection =[]
Input Types
Text Input
Unicode Normalization:
Text input values are normalized using NFC (Canonical Composition) by default if the intl extension is available. This ensures consistent character representation (e.g., Japanese combining marks: か゛ → が).
For normalization form details, see Normalizer class documentation.
Email Input
URL Input
UrlInput validates URLs using PHP's FILTER_VALIDATE_URL. It converts full-width characters to half-width and trims whitespace. You can restrict allowed schemes (default: http, https).
Telephone Input
TelInput strips all formatting characters (spaces, hyphens, parentheses) but preserves a leading + for international E.164 format. It does NOT validate phone numbers - use libphonenumber for validation and formatting:
Select Input
Multi-Select Input
Number Inputs
Note on IntegerInput limits:
- IntegerInput validates values against PHP_INT_MIN to PHP_INT_MAX range
- Values outside this range (e.g., very large database bigint IDs) will fail validation with TooLargeError/TooSmallError
getInteger()returns null for values outside PHP int range- For very large integers (e.g., Twitter snowflake IDs, large database bigints), use TextInput instead
Date Input
Boolean Input
BooleanInput considers only '', null, and false as "empty" (false).
Everything else including '0', 0, 'off', 'no' is considered "not empty" (true).
File Input
FileInput validates files by their path. It checks file size, MIME type, and extension. This library does not handle HTTP file uploads ($_FILES) - that should be done by your HTTP layer.
FileInput works with file paths (strings), not $_FILES arrays. For tracking uploaded files across form submissions, use a separate TextInput for file ID.
Example upload flow:
Nested Forms
Repeating Forms
RepeatingForm manages dynamic lists of form items using a factory pattern:
Factory Function
The factory function receives an index parameter:
Nested Repeating Forms
RepeatingForm can contain other forms, including nested RepeatingForms:
Items can be added programmatically:
Derived Inputs
Derived inputs are special form items that depend on other form items. They can:
- Calculate values from source inputs (e.g., full name from first + last name)
- Perform cross-field validation (e.g., password confirmation matching)
- Track external validation results (e.g., authentication status)
Key Properties:
- Always read-only - their value comes from sources, not user input
- Return
nullif any source input fails validation - Can have both value calculation (
setValueCalculator) and validation (setValidator)
Basic Example: Calculated Values
More Calculation Examples
Cross-Field Validation
Use setValidator() to validate relationships between fields. The validator receives:
- All source values as individual parameters
- The calculated value as the last parameter (or
nullif no calculator)
The validator returns an Error object if invalid, or null if valid.
Note: Derived validation only runs if all source inputs pass their own validation first. If any source fails, the Derived item automatically gets a SourceItemInvalidError.
Combined: Calculation with Validation
You can use both setValueCalculator() and setValidator() together:
Complete Example
Configuration
UTF-8 Invalid Character Handling
This library assumes all input is UTF-8 encoded. Invalid UTF-8 byte sequences are automatically replaced with a substitute character during filtering.
By default, PHP uses ? (U+003F QUESTION MARK) as the substitute character. For better visibility of data corruption, it's recommended to use � (U+FFFD REPLACEMENT CHARACTER) instead by configuring it in your application bootstrap:
Alternative configurations:
See mb_substitute_character documentation for more options.
API Reference
Form
Input
All input types extend Input and support:
Text Input
Select/MultiSelect
Number Inputs
Boolean Input
File Input
RepeatingForm
License
MIT
All versions of form with dependencies
ext-mbstring Version *
ext-bcmath Version *
ext-fileinfo Version *
ext-filter Version *