Form Validation
User input is untrusted until it has been validated. CodeIgniter's validation service checks rules, returns clear errors, and integrates with old input and the form helper.
The form
<form method="post" action="<?= site_url('contact/send') ?>">
<input type="hidden" name="<?= csrf_token() ?>" value="<?= csrf_hash() ?>">
<label>Email</label>
<input type="email" name="email" value="<?= esc(old('email')) ?>">
<label>Message</label>
<textarea name="message"><?= esc(old('message')) ?></textarea>
<button type="submit">Send</button>
</form>
Validate in the controller
public function send()
{
$rules = [
'email' => 'required|valid_email',
'message' => 'required|min_length[10]|max_length[2000]',
];
if (! $this->validate($rules)) {
return redirect()->back()
->withInput()
->with('errors', $this->validator->getErrors());
}
// Input is valid; continue with the saved data.
}
Display errors
<?php if (session()->has('errors')): ?>
<ul>
<?php foreach (session('errors') as $error): ?>
<li><?= esc($error) ?></li>
<?php endforeach; ?>
</ul>
<?php endif; ?>
Useful rules
required,permit_empty,valid_email,is_unique[users.email]min_length[],max_length[],numeric,decimalin_list[a,b,c],matches[password],regex_match[...]uploaded[file],max_size[file,2048],mime_in[file,image/png,image/jpeg]
Rules of thumb
Validate on the server even when the browser also validates. Escape values when you display them. Use CSRF protection for state-changing forms, and never trust a hidden field to enforce permissions.