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:

  1. A form is displayed.

  2. The user fills it and submits it.

  3. If invalid, the form is redisplayed with error messages and old values.

  4. 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 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

name($field)

Selects the input field by its name attribute. Supports field|Label syntax to set a friendly label used in error messages.

pattern($name, $custom_error)

Validates against a built-in named pattern. Available patterns: url, alpha, words, alphanum, int, float, tel, text, file, folder, address, date_dmy, date_ymd, email.

custom_pattern($regex, $custom_error)

Validates against a custom regular expression pattern.

required($custom_error)

Ensures the field is not empty or null.

matches($field, $custom_error)

Ensures the value matches the value of another field.

differs($field, $custom_error)

Ensures the value is different from another field’s value.

is_unique($table, $field, $str, $custom_error)

Checks that the value does not already exist in the specified database table column.

exact_length($length, $custom_error)

Ensures the string is exactly $length characters long.

min_length($length, $custom_error)

Ensures the string is at least $length characters long.

max_length($length, $custom_error)

Ensures the string does not exceed $length characters.

valid_email($custom_error)

Ensures the value is a properly formatted email address.

alpha($custom_error)

Allows only alphabetic characters (no spaces or numbers).

alpha_space($custom_error)

Allows alphabetic characters and spaces only.

alpha_numeric($custom_error)

Allows letters and numbers only (no spaces or special characters).

alpha_numeric_space($custom_error)

Allows letters, numbers, and spaces only.

alpha_numeric_dash($custom_error)

Allows letters, numbers, underscores, and dashes only.

numeric($custom_error)

Ensures the value is a valid numeric value (integer or decimal).

greater_than($value, $custom_error)

Ensures the numeric value is strictly greater than $value.

greater_than_equal_to($value, $custom_error)

Ensures the numeric value is greater than or equal to $value.

less_than($value, $custom_error)

Ensures the numeric value is strictly less than $value.

less_than_equal_to($value, $custom_error)

Ensures the numeric value is less than or equal to $value.

in_list($list, $custom_error)

Ensures the value is one of the comma-separated values in $list.

valid_name($custom_error)

Ensures the value is a valid person name (Unicode letters and spaces only).

rules($rules, $custom_errors)

Applies a pipe-separated rules string to the currently selected field. Does not run validation immediately.

run()

Runs the validation and returns TRUE if there are no errors.

validate($fields, $custom_errors)

Validates an array of field-rule pairs. Automatically resets previous errors. Returns TRUE if all rules pass.

submitted()

Returns TRUE if the form was submitted (i.e. $_POST is not empty).

errors()

Returns all validation error messages as a single HTML-escaped string, separated by <br> tags. Returns an empty string if there are no errors.

get_errors()

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

required

required

Field must not be empty.

valid_email

valid_email

Must be a valid email address.

valid_name

valid_name

Must be a valid person name (letters and spaces).

matches

matches[password]

Must match the value of the given field.

differs

differs[old_password]

Must differ from the value of the given field.

is_unique

(fluent only)

Value must not exist in the given database column.

min_length

min_length[8]

Minimum string length.

max_length

max_length[255]

Maximum string length.

exact_length

exact_length[10]

String must be exactly this many characters.

alpha

alpha

Letters only.

alpha_space

alpha_space

Letters and spaces only.

alpha_numeric

alpha_numeric

Letters and numbers only.

alpha_numeric_space

alpha_numeric_space

Letters, numbers, and spaces only.

alpha_numeric_dash

alpha_numeric_dash

Letters, numbers, underscores, and dashes only.

numeric

numeric

Must be a numeric value.

greater_than

greater_than[0]

Must be greater than the given number.

greater_than_equal_to

greater_than_equal_to[18]

Must be greater than or equal to the given number.

less_than

less_than[100]

Must be less than the given number.

less_than_equal_to

less_than_equal_to[999]

Must be less than or equal to the given number.

in_list

in_list[yes,no]

Must be one of the comma-separated values.

pattern

pattern[url]

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

required

"%s" is required.

matches

"%s" does not match the confirmation field.

differs

"%s" must be different from the other field.

is_unique

"%s" already exists. Please enter a unique value.

exact_length

"%s" must be exactly %d character(s) long.

min_length

"%s" must be at least %d character(s) long.

max_length

"%s" must not exceed %d character(s).

valid_email

"%s" must be a valid email address.

alpha

"%s" must contain letters only.

alpha_numeric

"%s" must contain letters and numbers only.

alpha_numeric_space

"%s" must contain letters, numbers, and spaces only.

alpha_space

"%s" must contain letters and spaces only.

alpha_numeric_dash

"%s" must contain letters, numbers, and dashes only.

numeric

"%s" must be a numeric value.

greater_than

"%s" must be greater than %s.

less_than

"%s" must be less than %s.

greater_than_equal_to

"%s" must be greater than or equal to %s.

less_than_equal_to

"%s" must be less than or equal to %s.

in_list

"%s" is not a valid option.

pattern / custom_pattern

"%s" does not match the required format.

valid_name

"%s" is not a valid name.