Form Validation Class
The Form Validation class allows you to validate form input data easily and cleanly. It handles checking for required fields, verifying data type, length, and uniqueness, as well as sanitizing and preparing data for database insertion.
Overview
Typical form validation process:
A form is displayed.
The user fills it and submits it.
If invalid, the form is redisplayed with error messages and old values.
If valid, the data is processed (e.g. saved to a database).
LavaLust provides a dedicated Form Validation library to simplify this process.
Form Validation Tutorial
You will need three parts:
A form view containing the input fields
A success view shown after successful submission
A controller to process and validate the data
The Form
Create myform.php in your app/views/ directory:
<html>
<head>
<title>My Form</title>
</head>
<body>
<?php $LAVA = lava_instance(); ?>
<?php echo $LAVA->form_validation->errors(); ?>
<form action="<?php echo site_url('form');?>" method="post">
<h5>Username</h5>
<input type="text" name="username" size="50" />
<h5>Password</h5>
<input type="password" name="password" size="50" />
<h5>Password Confirm</h5>
<input type="password" name="passconf" size="50" />
<h5>Email Address</h5>
<input type="text" name="email" size="50" />
<div><input type="submit" value="Submit" /></div>
</form>
</body>
</html>
The Success Page
Create formsuccess.php in app/views/:
<html>
<head>
<title>Form Success</title>
</head>
<body>
<h3>Your form was successfully submitted!</h3>
</body>
</html>
The Controller
Create Form.php in app/controllers/:
<?php
class Form extends Controller {
public function index()
{
$this->call->library('form_validation');
if ($this->form_validation->validate([
'username|Username' => 'required|min_length[5]|max_length[20]',
'password|Password' => 'required|min_length[8]',
'passconf|Confirm Password' => 'required|matches[password]',
'email|Email Address' => 'required|valid_email'
]))
{
$this->call->view('formsuccess');
}
else
{
$this->call->view('myform');
}
}
}
Trying It Out
Visit your form in the browser:
example.com/index.php/form/
Submit the form without filling in any fields. Validation will fail and error messages
will be displayed above the form. The validate() method returns TRUE only when
all validation rules pass.
Validation Approaches
LavaLust supports three ways to run validation. The ``validate()`` method is recommended for most use cases. The ``rules()`` method is useful for setting rules before running validation manually. The fluent/legacy style is still fully supported for backward compatibility.
Using validate() — Recommended
The validate() method accepts a rules array and an optional custom errors array.
It resets previous errors automatically and returns TRUE if all rules pass.
Basic example:
if ($this->form_validation->validate([
'username|Username' => 'required|min_length[5]|max_length[20]',
'email|Email Address' => 'required|valid_email',
])) {
// Validation passed — process the data
} else {
// Validation failed — redisplay the form
}
Full registration form example:
$this->form_validation->validate([
'username|Username' => 'required|alpha_numeric_dash|min_length[5]|max_length[30]',
'full_name|Full Name' => 'required|valid_name|max_length[100]',
'email|Email Address' => 'required|valid_email',
'password|Password' => 'required|min_length[8]|max_length[64]',
'passconf|Confirm Password' => 'required|matches[password]',
'age|Age' => 'required|numeric|greater_than[17]|less_than_equal_to[120]',
'website|Website' => 'pattern[url]',
'role|Role' => 'required|in_list[admin,editor,viewer]',
]);
Using the ``field|Label`` syntax:
Use field_name|Label as the array key to show a friendly label in error messages
instead of the raw field name.
$this->form_validation->validate([
'dob|Date of Birth' => 'required|pattern[date_ymd]',
'phone|Phone Number' => 'required|pattern[tel]',
]);
// Error example: "Date of Birth" does not match the required format.
With custom error messages:
Pass a second array to override specific default messages per field and per rule.
$this->form_validation->validate([
'username|Username' => 'required|min_length[5]|max_length[20]|alpha_numeric_dash',
'email|Email Address' => 'required|valid_email',
'password|Password' => 'required|min_length[8]',
], [
'username' => [
'required' => 'Please choose a username.',
'min_length' => 'Your username must be at least 5 characters long.',
'max_length' => 'Your username must not exceed 20 characters.',
'alpha_numeric_dash' => 'Your username may only contain letters, numbers, and dashes.',
],
'email' => [
'required' => 'An email address is required to create your account.',
'valid_email' => 'Please enter a valid email address (e.g. user@example.com).',
],
'password' => [
'required' => 'A password is required.',
'min_length' => 'Your password must be at least 8 characters long.',
],
]);
Product/inventory form example:
$this->form_validation->validate([
'product_name|Product Name' => 'required|alpha_numeric_space|max_length[150]',
'sku|SKU' => 'required|alpha_numeric_dash|exact_length[10]',
'price|Price' => 'required|numeric|greater_than[0]',
'stock|Stock' => 'required|numeric|greater_than_equal_to[0]',
'category|Category' => 'required|in_list[electronics,clothing,food,tools]',
], [
'sku' => [
'exact_length' => 'SKU must be exactly 10 characters.',
],
'price' => [
'greater_than' => 'Price must be greater than 0.',
],
]);
Using rules() — Manual Validation
The rules() method sets validation rules for the currently selected field
without running the validation immediately. Combine it with name() and run()
for full control over when validation executes.
Basic example:
$this->form_validation
->name('username|Username')->rules('required|min_length[5]|max_length[20]')
->name('email|Email Address')->rules('required|valid_email');
if ($this->form_validation->run()) {
$this->call->view('formsuccess');
} else {
$this->call->view('myform');
}
With custom error messages:
$this->form_validation
->name('username|Username')
->rules('required|min_length[5]', [
'required' => 'Please enter your username.',
'min_length' => 'Username must be at least 5 characters.',
])
->name('email|Email Address')
->rules('required|valid_email', [
'valid_email' => 'Please enter a valid email address.',
]);
if ($this->form_validation->run()) {
$this->call->view('formsuccess');
} else {
$this->call->view('myform');
}
Conditional rule application example:
$this->form_validation
->name('email|Email Address')
->rules('required|valid_email');
// Only validate password confirmation if a new password is provided
if (!empty($_POST['password'])) {
$this->form_validation
->name('password|Password')
->rules('required|min_length[8]')
->name('passconf|Confirm Password')
->rules('required|matches[password]');
}
if ($this->form_validation->run()) {
// Process update
}
Multi-step form example (step 2 only):
$step = $_POST['step'] ?? 1;
if ((int) $step === 2) {
$this->form_validation
->name('card_number|Card Number')->rules('required|exact_length[16]|numeric')
->name('cvv|CVV')->rules('required|exact_length[3]|numeric')
->name('expiry|Expiry Date')->rules('required|pattern[date_ymd]');
}
if ($this->form_validation->run()) {
// Proceed to step 3
}
Legacy / Fluent Style
The original method-chaining style is still fully supported. Call name() to
select a field, then chain validation methods directly onto it.
Basic example:
$this->form_validation
->name('username')
->required()
->min_length(5)
->max_length(20)
->name('password')
->required()
->min_length(8)
->name('passconf')
->required()
->matches('password')
->name('email')
->required()
->valid_email();
if ($this->form_validation->run()) {
$this->call->view('formsuccess');
} else {
$this->call->view('myform');
}
With custom error messages:
Each fluent method accepts an optional $custom_error string as its last argument.
$this->form_validation
->name('username|Username')
->required('Please enter your username.')
->min_length(5, 'Username must be at least 5 characters long.')
->max_length(20, 'Username must not exceed 20 characters.')
->alpha_numeric_dash('Username may only contain letters, numbers, and dashes.')
->name('email|Email Address')
->required('An email address is required.')
->valid_email('Please enter a valid email address.')
->name('password|Password')
->required('A password is required.')
->min_length(8, 'Password must be at least 8 characters long.')
->name('passconf|Confirm Password')
->required('Please confirm your password.')
->matches('password', 'Passwords do not match.');
if ($this->form_validation->run()) {
$this->call->view('formsuccess');
} else {
$this->call->view('myform');
}
Numeric and range validation example:
$this->form_validation
->name('age|Age')
->required()
->numeric()
->greater_than(17, 'You must be at least 18 years old.')
->less_than_equal_to(120, 'Please enter a valid age.')
->name('score|Score')
->required()
->numeric()
->greater_than_equal_to(0, 'Score cannot be negative.')
->less_than_equal_to(100, 'Score cannot exceed 100.');
if ($this->form_validation->run()) {
// Process data
}
Pattern and uniqueness example:
$this->form_validation
->name('username|Username')
->required()
->min_length(5)
->is_unique('users', 'username', $_POST['username'] ?? '', 'That username is already taken.')
->name('website|Website')
->pattern('url', 'Please enter a valid URL.')
->name('birthdate|Date of Birth')
->required()
->pattern('date_ymd', 'Please use the format YYYY-MM-DD.')
->name('phone|Phone Number')
->pattern('tel', 'Please enter a valid phone number.');
if ($this->form_validation->run()) {
// Process data
}
Using submitted()
Check whether the form was actually submitted before running validation:
public function index()
{
$this->call->library('form_validation');
if ($this->form_validation->submitted()) {
if ($this->form_validation->validate([
'username|Username' => 'required|min_length[5]',
'email|Email Address' => 'required|valid_email',
])) {
$this->call->view('formsuccess');
} else {
$this->call->view('myform');
}
} else {
// Form has not been submitted yet — just display it
$this->call->view('myform');
}
}
Displaying Errors
Call errors() in your view to output all validation error messages as a
newline-separated string. It returns an empty string when there are no errors.
<?php echo $this->form_validation->errors(); ?>
For styled output, wrap it in a container:
<?php $errors = $this->form_validation->errors(); ?>
<?php if ($errors): ?>
<div class="alert alert-danger">
<?php echo $errors; ?>
</div>
<?php endif; ?>
To retrieve errors as a raw array (e.g. for JSON responses or custom rendering):
$errors = $this->form_validation->get_errors();
if (!empty($errors)) {
echo json_encode(['success' => false, 'errors' => $errors]);
exit;
}
Available Methods
Method |
Description |
|---|---|
|
Selects the input field by its |
|
Validates against a built-in named pattern. Available patterns:
|
|
Validates against a custom regular expression pattern. |
|
Ensures the field is not empty or null. |
|
Ensures the value matches the value of another field. |
|
Ensures the value is different from another field’s value. |
|
Checks that the value does not already exist in the specified database table column. |
|
Ensures the string is exactly |
|
Ensures the string is at least |
|
Ensures the string does not exceed |
|
Ensures the value is a properly formatted email address. |
|
Allows only alphabetic characters (no spaces or numbers). |
|
Allows alphabetic characters and spaces only. |
|
Allows letters and numbers only (no spaces or special characters). |
|
Allows letters, numbers, and spaces only. |
|
Allows letters, numbers, underscores, and dashes only. |
|
Ensures the value is a valid numeric value (integer or decimal). |
|
Ensures the numeric value is strictly greater than |
|
Ensures the numeric value is greater than or equal to |
|
Ensures the numeric value is strictly less than |
|
Ensures the numeric value is less than or equal to |
|
Ensures the value is one of the comma-separated values in |
|
Ensures the value is a valid person name (Unicode letters and spaces only). |
|
Applies a pipe-separated rules string to the currently selected field. Does not run validation immediately. |
|
Runs the validation and returns TRUE if there are no errors. |
|
Validates an array of field-rule pairs. Automatically resets previous errors. Returns TRUE if all rules pass. |
|
Returns TRUE if the form was submitted (i.e. |
|
Returns all validation error messages as a single HTML-escaped string,
separated by |
|
Returns a raw array of all current validation error messages. |
Note
Every validation method accepts an optional $custom_error string as its
final argument to override the default error message for that specific rule.
Note
The validate() method resets all previous errors at the start of each call,
making it safe to call multiple times within the same request without accumulating
stale errors. When using the fluent style with run(), errors accumulate across
all chained calls until run() is invoked.
Rule Reference
The table below summarises every built-in rule available for use in validate()
and rules() rule strings.
Rule |
Example |
Description |
|---|---|---|
|
|
Field must not be empty. |
|
|
Must be a valid email address. |
|
|
Must be a valid person name (letters and spaces). |
|
|
Must match the value of the given field. |
|
|
Must differ from the value of the given field. |
|
(fluent only) |
Value must not exist in the given database column. |
|
|
Minimum string length. |
|
|
Maximum string length. |
|
|
String must be exactly this many characters. |
|
|
Letters only. |
|
|
Letters and spaces only. |
|
|
Letters and numbers only. |
|
|
Letters, numbers, and spaces only. |
|
|
Letters, numbers, underscores, and dashes only. |
|
|
Must be a numeric value. |
|
|
Must be greater than the given number. |
|
|
Must be greater than or equal to the given number. |
|
|
Must be less than the given number. |
|
|
Must be less than or equal to the given number. |
|
|
Must be one of the comma-separated values. |
|
|
Must match a built-in named pattern. |
Default Error Messages
The following messages are used when no custom error is provided. The %s
placeholder is replaced with the field label; %d is replaced with the
numeric parameter where applicable.
Rule |
Default Message |
|---|---|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|