kodhe / validation
Kodhe Form Validation
Requires
- php: >=8.1
Requires (Dev)
None
Suggests
None
Provides
None
Conflicts
None
Replaces
None
This package is not auto-updated.
Last update: 2026-10-28 12:49:41 UTC
README
A form validation package — a refactored version of the CodeIgniter 3 Form_validation library with a modern namespace (Kodhe\Framework\Validation). It works both for validating POST/GET input in CI3-style applications and standalone via set_data(). It ships with form helpers (form_open, form_input, etc.) and a new modular layer (validator factory, rule parser, message manager) under src/.
Installation
composer require kodhe/validation
Requirements: PHP >= 8.1. The validation/src/helpers/form.php helper is autoloaded automatically via composer.json (the files key).
Quick Start
<?php declare(strict_types=1); require __DIR__ . '/vendor/autoload.php'; use Kodhe\Framework\Validation\FormValidation; $validation = new FormValidation(); $validation->set_rules('username', 'Username', 'required|alpha_numeric|min_length[4]|max_length[20]'); $validation->set_rules('email', 'Email', 'required|valid_email'); $validation->set_rules('password', 'Password', 'required|min_length[8]|matches[password_confirm]'); if ($validation->run() === false) { // There are errors — show them per field or all at once echo $validation->error('email'); // <p>The Email field must contain a valid email address.</p> echo $validation->error_string(); // all errors combined } else { // Valid — continue processing }
Note: without a CodeIgniter instance,
run()reads data from$_POST. Useset_data()for other data sources.
Directory Structure
src/
├── FormValidation.php # Main class (CI3-compatible API)
├── Exceptions/ # ValidationException, RuleNotFoundException
├── Factory/ValidatorFactory.php
├── Filters/BaseFilter.php
├── Messages/MessageManager.php
├── Contracts/ # ValidatorInterface, FilterInterface, RuleInterface
├── Support/ # RuleParser, RuleCache
├── Validators/ # RequiredValidator, EmailValidator, RegexValidator, ...
├── ValueObjects/ # ValidationError, FieldConfig
└── helpers/form.php # HTML form helpers (form_open, form_input, ...)
Usage
1. Validating non-POST data (set_data)
$validation->set_data([ 'name' => 'John', 'age' => '17', ]); $validation->set_rules('name', 'Name', 'required|alpha'); $validation->set_rules('age', 'Age', 'required|integer|greater_than[17]'); if ($validation->run()) { // passes }
2. Displaying errors
// One field's error (uses the default <p>...</p> delimiters) echo $validation->error('name'); // One field's error with custom delimiters echo $validation->error('name', '<span class="err">', '</span>'); // All errors as an array: ['field' => 'message', ...] $errors = $validation->error_array(); // All errors as a single string echo $validation->error_string('<div>', '</div>'); // Replace the global delimiters $validation->set_error_delimiters('<em>', '</em>');
3. Custom error messages
$validation->set_rules('email', 'Email', 'required|valid_email'); // Per ruleset $validation->set_message('required', 'The %s field is required.'); $validation->set_message('valid_email', 'The %s format is invalid.'); // Per field (higher priority): key format = {rules}_{field} $validation->set_message('required_email', 'Please provide your email address.');
The %s placeholder is replaced with the field label.
4. Form repopulation (form helpers)
<input type="text" name="username" value="<?php echo set_value('username'); ?>"> <input type="checkbox" name="hobbies[]" value="fishing" <?php echo set_checkbox('hobbies[]', 'fishing'); ?>>
set_value() / set_select() / set_radio() / set_checkbox() are FormValidation methods that read the last POST data so the form is repopulated after a validation failure.
5. Built-in rules
| Category | Rules |
|---|---|
| General | required, regex_match[/.../], matches[field], differs[field], is_unique[table.field]* |
| String | min_length[n], max_length[n], exact_length[n], alpha, alpha_numeric, alpha_numeric_spaces, alpha_dash |
| Numeric | numeric, integer, decimal, greater_than[n], greater_than_equal_to[n], less_than[n], less_than_equal_to[n], in_list[a,b,c], is_natural, is_natural_no_zero |
| Format | valid_email, valid_emails, valid_url, valid_ip, valid_base64 |
| Sanitization | prep_for_form, prep_url, strip_image_tags, encode_php_tags |
* is_unique requires an active database connection.
Rules are chained with pipes: 'required|min_length[5]'.
6. Custom callback rules
class Book_model { // Used in rules as 'callback_check_title' public function check_title($str) { if ($str === strip_tags($str)) { return true; } $this->form_validation->set_message('check_title', 'The title must not contain HTML.'); return false; } }
7. Reset & rule checks
$validation->has_rule('email'); // bool $validation->reset_validation(); // clears all state
Configuration
The constructor accepts a CI3-format rules array:
$rules = [ ['field' => 'email', 'label' => 'Email', 'rules' => 'required|valid_email'], ]; $validation = new FormValidation($rules);
Or chain calls to set_rules($field, $label, $rules, $errors) as shown in the Quick Start.
API Reference (summary)
| Method | Description |
|---|---|
set_rules($field, $label, $rules, $errors) |
Registers the rules for a field |
set_data(array $data) |
Replaces the data source (default $_POST) |
run($group = '') |
Runs the validation; returns bool |
error($field, $prefix, $suffix) |
One field's error message |
error_array() |
All errors as an array |
error_string($prefix, $suffix) |
All errors as a string |
set_message($lang, $val) |
Custom message per rule/field |
set_error_delimiters($open, $close) |
Error-wrapping delimiters |
set_value/set_select/set_radio/set_checkbox |
Form repopulation |
has_rule($field) / reset_validation() |
Introspection & reset |
CodeIgniter 3 Compatibility
The FormValidation API is identical to CI3's CI_Form_validation — a drop-in replacement. Differences: the class name FormValidation (not Form_validation) and the Kodhe\Framework\Validation namespace. When run inside a CI3 application, internal CI references still resolve to the CI instance, so is_unique and the form helpers work normally.
Notes
is_unique[...]requires a connected database (enableautoload['database']).- The modular layer (
Factory/,Validators/,Support/,Messages/) is still evolving; the stable public API isFormValidation.
Testing
vendor/bin/phpunit --filter Validation
See tests/ for end-to-end usage examples.