CodeIgniter 4 has a powerful validation library. In controllers use $this->validate($rules) (checks request input) or $this->validateData($data, $rules) (checks an array).
Common rules
Combine rules with |:
required,permit_emptymin_length[3],max_length[255],exact_length[10]valid_email,valid_url,numeric,integer,alpha_spaceis_unique[users.email]— not already in the tablematches[password]— same as another fieldin_list[draft,published]greater_than[0],regex_match[/^[0-9]{10}$/]
Custom messages
Pass messages as the second argument: ['email' => ['is_unique' => 'This email is already registered.']].
Showing errors
After redirect()->back()->withInput(), the view can use:
validation_list_errors()— all errors as a listvalidation_show_error('email')— the error for one fieldold('email')orset_value('email')— refill the field
Getting clean data
$this->validator->getValidated() returns only the fields that were validated.
You can also put rules in a model's $validationRules, or in app/Config/Validation.php as named rule groups.
Example
<?php
public function register()
{
$rules = [
'name' => 'required|min_length[3]|max_length[100]',
'email' => 'required|valid_email|is_unique[users.email]',
'mobile' => 'required|regex_match[/^[6-9][0-9]{9}$/]',
'password' => 'required|min_length[8]',
'password_confirm' => 'required|matches[password]',
];
$messages = [
'email' => ['is_unique' => 'This email is already registered.'],
'mobile' => ['regex_match' => 'Enter a valid 10-digit mobile number.'],
];
if (! $this->validate($rules, $messages)) {
return redirect()->back()->withInput();
}
$data = $this->validator->getValidated();
unset($data['password_confirm']);
$data['password'] = password_hash($data['password'], PASSWORD_DEFAULT);
model('UserModel')->insert($data);
return redirect()->to('login')->with('success', 'Account created. Please log in.');
}
// View:
// <input name="email" value="<?= old('email') ?>">
// <span class="text-danger"><?= validation_show_error('email') ?></span>
If the email is taken, the form comes back with "This email is already registered." under the email field and the other fields still filled in.