CodeIgniter 4 - Form Validation Example

Posted by Ridwan Fadilah on Jul 16, 2020 - 05:51 pm

Form Validation Example

Learn about how to make Form Validation in CodeIgniter 4. Validation and rules example.

The form validation is used to check the required data and verify that the users have to input the correct data. For example, if the user will submit an email, it must have a unique email.

Now, in this tutorial, I'll show you how to make form validation in CodeIgniter 4.

The Form

Here I'll use bootstrap form. I also use the 'session' to display the validation error on the page.

Important to note: Here, I have an 'article' controller with the 'create' method, so, I set the form action attribute to action="/article/create". Be sure you have an exact controller and method.

Form:

<form action="/article/create" method="post" enctype="multipart/form-data">
<?= csrf_field(); ?>
<div class="form-group my-3">
<label for="author">Author</label>
<input type="text" class="form-control <?= ($validation->hasError('author')) ? 'is-invalid' : ''; ?>" name="author" value="<?= old('author'); ?>">
<div class="invalid-feedback">
<?= $validation->getError('author'); ?>
</div>
</div>

<div class="form-group my-3">
<label for="title">Title</label>
<input type="text" class="form-control <?= ($validation->hasError('title')) ? 'is-invalid' : ''; ?>" name="title" value="<?= old('title'); ?>">
<div class="invalid-feedback">
<?= $validation->getError('title'); ?>
</div>
</div>

<div class="form-group my-3">
<label for="description">Description</label>
<input type="text" class="form-control <?= ($validation->hasError('description')) ? 'is-invalid' : ''; ?>" name="description" value="<?= old('description'); ?>">
<div class="invalid-feedback">
<?= $validation->getError('description'); ?>
</div>
</div>

<div class="form-group my-3">
<label for="date_create"></label>
<input type="hidden" class="form-control" name="date_create" value="<?= date('D, d M Y H:i:s'); ?>">
</div>

<div class="form-group my-3">
<label for="content">Content</label>
<textarea type="text" class="form-control <?= ($validation->hasError('content')) ? 'is-invalid' : ''; ?>" name="content" rows="7"><?= old('content'); ?></textarea>
<div class="invalid-feedback">
<?= $validation->getError('content'); ?>
</div>
</div>

<button type="button" class="btn btn-secondary" onclick="window.location.href='<?= base_url('article'); ?>'">Back</button>
<button type="submit" class="btn btn-primary">Save</button>
</form>

The csrf_field(); will return a string with the HTML for hidden input with all required CSRF information.

The old() will keep the value of the input field when the form is not valid.

The date('D, d M Y H:i:s'); is the date and time.

The <?= ($validation->hasError()) ? 'is-invalid' : ''; ?> is the ternary operator ('if' and 'else' conditional statement in one line). The code can be described like this:
If the validation for (field name) has an error, add the is-invalid class.

The is-invalid is a Bootstrap class for invalid field.

The <?= $validation->getError('description'); ?> will display the error message.

The Controller

You need to display the form view in the controller first. My form page is newpost.php, so, to call and display that, I need to make the method in my controller.

Displaying the form (Controller):

public function newPost()
{
session();

$data = [
'pageTitle' => 'Create a New Post',
'validation' => \Config\Services::validation()
];

return view('article/newpost', $data);
}

The session() is used to load the session. I use the session to send the error message when the validation has an error.

Now the form has displayed:

Form Page

Now, let's make the method that will manage the form submitted:

public function create()
{
// load model
$article = new ArticleModel();

// validation

if (!$this->validate([
'author' => 'required',
'title' => 'required|min_length[8]|is_unique[blog_article.title]',
'description' => 'required|min_length[100]',
'content' => 'required'
])) {

return redirect()->to('/article/newpost')->withInput();
}

$slug = url_title($this->request->getPost('title'), '-', true);
$article->save([
'author' => $this->request->getPost('author'),
'title' => $this->request->getPost('title'),
'slug' => $slug,
'description' => $this->request->getPost('description'),
'date_create' => $this->request->getPost('date_create'),
'content' => $this->request->getPost('content')
]);

return $this->response->redirect(site_url('article'));
}

The withInput(); is used to send the validation. We can't to send the validation using the $data variable with response->redirect.

I use getPost() for post method. You can also use the getVar(), that allows you to use both method (post and get). Or, use getGet() for get method.

The is_unique[blog_article.title] is used to checks if this field value exists in the database. Optionally set a column and value to ignore, useful when updating records to ignore itself.

is_unique[table.field,ignore_field,ignore_value]

Here's the validation above when displaying the error messages:

Validation Errors

Customizing Error Display

CodeIgniter allows for adding custom messages. You need to create the view first, but in this tutorial, you don't need to do it. You can use the div element with an invalid-feedback class in the form that has created to display the custom message.

I'll use a custom validation for the 'author' field.

Here's the example:

if (!$this->validate([
'author' => [
'rules' => 'required',
'errors' => [
'required' => 'Please input the author name. The author name is required!'
]
],
'title' => 'required|min_length[8]|is_unique[blog_article.title]',
'description' => 'required|min_length[100]',
'content' => 'required'
])) {

return redirect()->to('/article/newpost')->withInput();
}

Here's the built-in error message:

Built-in Error Message

and here's the custom error message:

Custom Error Message

Do the same for another field.

Okay, that's the tutorial about how to make form validation in CodeIgniter 4. Find another CodeIgniter tutorial on the related tutorial below. You can see another tutorial on our YouTube Channel. You can also find the full source code of these examples on our GitHub.

Thanks for reading, see you in the next article.


Related Articles