set_rules()
public function set_rules(string $key, string $label, string $rules): void
Description
Defines validation rules for a specific form field or file upload. This method is the foundation of Trongate's validation system, allowing you to specify which fields are required, what format they should have, and what constraints they must meet. Each call to set_rules() validates one field according to the specified rules.
Quick Start: Call set_rules() for each field you want to validate, then call $this->validation->run() to execute all validations at once.
Parameters
| Parameter | Type | Description |
|---|---|---|
| $key | string | The name attribute of the form field (e.g., 'email', 'password', 'task_title'). |
| $label | string | A human-readable label used in error messages (e.g., 'Email Address', 'Password', 'Task Title'). |
| $rules | string | Validation rules separated by pipe characters (|). For rules requiring parameters, use square brackets (e.g., 'required|min_length[8]|max_length[255]'). |
Return Value
| Type | Description |
|---|---|
| void | This method does not return a value. Errors are stored internally and retrieved via validation_errors(). |
Available Validation Rules
Basic Rules
| Rule | Description | Example |
|---|---|---|
required |
Field must not be empty | 'required' |
numeric |
Field must contain only numbers | 'numeric' |
integer |
Field must be a whole number (no decimals) | 'integer' |
decimal |
Field must contain a decimal number | 'decimal' |
valid_email |
Field must be a valid email address with DNS verification | 'valid_email' |
Length Rules
| Rule | Description | Example |
|---|---|---|
min_length[n] |
Field must be at least n characters long | 'min_length[8]' |
max_length[n] |
Field must be no more than n characters long | 'max_length[255]' |
exact_length[n] |
Field must be exactly n characters long | 'exact_length[10]' |
Comparison Rules
| Rule | Description | Example |
|---|---|---|
matches[field] |
Field must match another field (useful for password confirmation) | 'matches[password]' |
differs[field] |
Field must not match another field | 'differs[old_password]' |
greater_than[n] |
Numeric field must be greater than n | 'greater_than[0]' |
less_than[n] |
Numeric field must be less than n | 'less_than[100]' |
Date and Time Rules
| Rule | Description | Example |
|---|---|---|
valid_date |
Field must be a valid date in YYYY-MM-DD format | 'valid_date' |
valid_time |
Field must be a valid time in HH:MM or HH:MM:SS format | 'valid_time' |
valid_datetime_local |
Field must be a valid datetime in YYYY-MM-DDTHH:MM format | 'valid_datetime_local' |
valid_month |
Field must be a valid month in YYYY-MM format | 'valid_month' |
valid_week |
Field must be a valid week in YYYY-W## format (e.g., 2025-W52) | 'valid_week' |
File Upload Rules
| Rule | Description | Example |
|---|---|---|
allowed_types[ext1,ext2] |
File must have one of the specified extensions | 'allowed_types[jpg,png,gif]' |
max_size[kb] |
File size must not exceed specified kilobytes | 'max_size[2048]' |
max_width[px] |
Image width must not exceed specified pixels | 'max_width[1920]' |
max_height[px] |
Image height must not exceed specified pixels | 'max_height[1080]' |
min_width[px] |
Image width must be at least specified pixels | 'min_width[800]' |
min_height[px] |
Image height must be at least specified pixels | 'min_height[600]' |
square |
Image must be square (width equals height) | 'square' |
Custom Validation Rules
| Rule | Description | Example |
|---|---|---|
callback_method_name |
Calls a custom validation method in your controller | 'callback_check_username' |
Basic Usage Pattern
Simple Form Validation
This is the most common pattern for validating form submissions:
public function submit(): void {
$this->trongate_security->make_sure_allowed();
$submit = post('submit', true);
if ($submit === 'Submit') {
// Define validation rules for each field
$this->validation->set_rules('task_title', 'Task Title', 'required|min_length[2]|max_length[255]');
$this->validation->set_rules('task_description', 'Task Description', 'required|min_length[2]');
// Run all validations
if ($this->validation->run() === true) {
// Validation passed - process the form
$data = [
'task_title' => post('task_title', true),
'task_description' => post('task_description', true)
];
$this->db->insert($data, 'tasks');
redirect('tasks/manage');
} else {
// Validation failed - redisplay form with errors
$this->create();
}
}
}Advanced Examples
Example #1: User Registration Form
public function submit_registration(): void {
// Username validation
$this->validation->set_rules('username', 'Username', 'required|min_length[3]|max_length[50]|callback_check_username_available');
// Email validation with DNS checking
$this->validation->set_rules('email', 'Email Address', 'required|valid_email');
// Password validation with confirmation
$this->validation->set_rules('password', 'Password', 'required|min_length[8]|max_length[255]');
$this->validation->set_rules('password_confirm', 'Password Confirmation', 'required|matches[password]');
// Age validation
$this->validation->set_rules('age', 'Age', 'required|integer|greater_than[17]|less_than[120]');
if ($this->validation->run() === true) {
// Process registration...
} else {
$this->register(); // Redisplay with errors
}
}Example #2: File Upload Validation
public function submit_profile_photo(): void {
// Validate uploaded image
$this->validation->set_rules('profile_photo', 'Profile Photo', 'required|allowed_types[jpg,jpeg,png]|max_size[2048]|square|max_width[1000]|max_height[1000]');
if ($this->validation->run() === true) {
// Process file upload...
$file = $_FILES['profile_photo'];
// Handle file storage...
} else {
$this->upload_form();
}
}Example #3: Custom Callback Validation
public function submit(): void {
// Use custom validation callback
$this->validation->set_rules('username', 'Username', 'required|callback_check_username_unique');
if ($this->validation->run() === true) {
// Username is unique and valid...
}
}
/**
* Custom validation callback to check username uniqueness
*
* @param string $submitted_username The username to validate
* @return string|bool Returns error message string if invalid, true if valid
*/
public function check_username_unique(string $submitted_username): string|bool {
$existing = $this->db->get_one_where('username', $submitted_username, 'users');
if ($existing) {
return 'The {label} is already taken. Please choose another.';
}
return true;
}Callback Return Values: Custom validation methods must return true for success or a string error message for failure. Use {label} as a placeholder in your error message, which will be replaced with the field label.
Example #4: Date Range Validation
public function submit_booking(): void {
$this->validation->set_rules('start_date', 'Start Date', 'required|valid_date');
$this->validation->set_rules('end_date', 'End Date', 'required|valid_date|callback_check_date_range');
$this->validation->set_rules('check_in_time', 'Check-in Time', 'required|valid_time');
if ($this->validation->run() === true) {
// Process booking...
}
}
public function check_date_range(string $end_date): string|bool {
$start = post('start_date', true);
$end = post('end_date', true);
if (strtotime($end) <= strtotime($start)) {
return 'The {label} must be after the Start Date.';
}
return true;
}Combining Multiple Rules
Rules are separated by pipe characters and evaluated in order from left to right:
// All rules must pass for validation to succeed
$this->validation->set_rules('email', 'Email Address', 'required|valid_email|max_length[254]');
// If 'required' fails, other rules are still checked
$this->validation->set_rules('phone', 'Phone Number', 'required|exact_length[10]|numeric');
// Combining length and comparison rules
$this->validation->set_rules('price', 'Price', 'required|numeric|greater_than[0]|less_than[10000]');File Upload Validation Details
Automatic File Security: When validating file uploads, Trongate automatically scans the first 256 bytes of uploaded files for dangerous patterns like PHP code, shell commands, and malicious scripts. This security check happens before any custom validation rules are applied.
Complete File Upload Example
<!-- In your view -->
<?php
echo form_open_upload('documents/submit');
echo form_label('Document');
echo form_file_select('document');
echo form_submit('submit', 'Upload');
echo form_close();
?>// In your controller
public function submit(): void {
$this->validation->set_rules('document', 'Document', 'required|allowed_types[pdf,doc,docx]|max_size[5120]');
if ($this->validation->run() === true) {
// File passed validation - safe to process
$file = $_FILES['document'];
$destination = APPPATH . 'public/uploads/' . $file['name'];
move_uploaded_file($file['tmp_name'], $destination);
set_flashdata('Document uploaded successfully');
redirect('documents/manage');
} else {
$this->upload_form();
}
}Important Notes
- Order matters:
set_rules()calls are processed in the order they're written. Userequiredfirst for fields that must have a value. - Empty fields skip rules: Most validation rules (except
required) are automatically skipped if a field is empty. This allows optional fields to have format requirements. - Automatic cleaning: Field values are automatically retrieved with
post($key, true), which trims whitespace and collapses multiple spaces. - CSRF protection: CSRF validation happens automatically when
$this->validation->run()is called. - Error storage: Validation errors are stored in the session, allowing them to persist across redirects.
- Field labels in errors: The
$labelparameter is used in all error messages, making them more user-friendly.
Common Validation Patterns
| Field Type | Typical Rules |
|---|---|
| Username | 'required|min_length[3]|max_length[50]' |
'required|valid_email|max_length[254]' |
|
| Password | 'required|min_length[8]|max_length[255]' |
| Phone (10 digits) | 'required|exact_length[10]|numeric' |
| Age | 'required|integer|greater_than[0]|less_than[150]' |
| Price | 'required|numeric|greater_than[0]' |
| ZIP Code (5 digits) | 'required|exact_length[5]|numeric' |
| Optional URL | 'valid_url' (no required) |
Error Handling
After calling set_rules(), use $this->validation->run() to execute all validations. Display errors using validation_errors():
<!-- Display all errors at top of form -->
<?= validation_errors() ?>
<!-- Or display inline per-field errors -->
<?php
echo form_label('Email');
echo validation_errors('email');
echo form_input('email', post('email', true));
?>For more information on displaying validation errors, see the validation_errors() function documentation.