How to do form validation with custom rules in CodeIgniter 4 and MySQL

CodeIgniter 4 form validation can be done using built-in validation rules as well as by creating custom validatipon rules. We will create a registration form and validate the form data when user submits this form. In case validation fails, it will give error message. We will do callback validation as well in this example by creating custom rules along with email validation in CodeIgniter 4.

I will assume you have already got CodeIgniter 4 installed in your project root. All you have to do run below command in command line. For me, I installed in D:/projects, and I wanted my project name to be 'form', so I will run below command from D:/projects.

> composer create-project codeigniter4/appstarter form

This created a folder named 'form' in D:/projects and CodeIgniter4 is installed in that folder. See below:

form validation in CodeIgniter 4

If you want to know how to install and configure CodeIgniter 4, you can read the topic How to Install and Test CodeIgniter 4 in Your Local Computer

Below is a screenshot of the registration page:

Codeigniter 4 Form Validation Tutorial with Example

Form Validation Example in Codeigniter 4 For Beginners	Folders and Files

As I mentioned before, I have created a folder named 'projects' in D:\ drive and installed CodeIgniter4 in 'form' folder under projects. So, the project root directory is D:/projects/form.

Create Custom Validation Rule in CodeIgniter 4

You can see, we have Controller - Candidate.php, Model - ModelCandidate.php and the view - register.php. I have created a custom rule and it is added in CustomValidation folder. I have discussed this later. Folder 'assets' is created under public to keep all stylesheets, JavaScripts and image files. Here I have style.css which is kept in public/assets/css folder. Just make sure you give correct path for css file in the view.

There is a custom validation rule for age check. This is for age validation, as our form will accept only ages between 18 to 40, we need to validate the age value entered by the user. This is why ProjectRules.php is created under CustomValidation.

If you are using XAMPP and want to use Apache Web Server instead of PHP built-in server, then you can install CodeIgniter 4 under xampp/htdocs/<your folder name>. In our case this folder name is 'form'. I will show necessary configuration changes and testing the application for both the web servers.

Step 1 - Create a MySQL table to store candidate details

Let us create the table named 'candidates' in MySQL database. Table structures is given below:

Table: candidates

This table stores details of all candidates who completed successful registration.

CodeIgniter 4 Form Validation Example

Below are the columns in this table.

  1. candidate_id - It is the primary key and auto incremented id of the candidate
  2. name - Name of the candidate
  3. address - Address of the candidate
  4. email_id - Email Id of the candidate
  5. age - Age of the candidate
  6. registration_dt - Date of Registration
Create table script for this table are given below; you can use this code to create the table.

candidates.sql

Step 2 - Create the view for registration (register.php)

validation in codeigniter 4 with example

We will simply create a registration form with the fields for Name, Email Id, Address and Age. This Topic is more about form validation. So let's take a look at the code first:

app/Views/register.php

You can see in line 15, we have used $validation = \Config\Services::validation(), this will load the validation settings with rulesets which we can use in our validation. For each input field, an error message will be printed in case validation fails for that field. Once the form is submitted register() method of the Candidate controller is called.

Database setup and other configuration changes are discussed in step 5.

Step 3 - Write Controller code (Candidate.php)

Our controller function will have an index() method to display the register page and register() method to process submitted data. We will use the model ModelCandidate.php, so we need to create an instance of the model also. See below code at the beginning of the controller:

In the construct method, form and url helper are loaded. 'uri' and 'validation' services are also loaded. Then an instance of the model is created. index() method is executed by default in a controller. In this method it just loads the view to display registration form.

Controller Method register()

In this method we will do all the validations for the various input fields in the form.

If the form is submitted, it does validation for the input fields using validation rules. If validation is unsuccessful, it reloads the view with error message displayed corresponding to the field for which validation was failed. But if all fields are validated successfully, this method inserts the data in the table using the model. Let's see the code for register() method.

Just check for 'age' validation. We have used a custom rule 'ageCheck'. This is to validate allowed range of valid ages. We will discuss that how it is defined. $errors is for custom error messages in case validation fails.

If validation is successfully done, $this->model->save() method will insert the row in database table and return true or false.

Age validation

For age validation, we need to create a custom validation method. See the code below in ProjectRules.php under app/CustomValidation. This is like callback method used in CodeIgniter 3.

In this method, it checks the value of the input, if it falls between 18 and 40. If not, it returns false. Based on this, validation error message is displayed in the form.

Step 4 - Write Model code (ModelCandidate.php)

Our model is very simple, just defines the table name and updatable columns.

Let me give the stylesheet also I am using for all these views.

style.css

I just added few simple styles here, you can always add better styles.

Step 5 - Update Configuration files and Test the Application

Let us now update few setup files before we run the application.

We will update below files in Config folder and also, we will have .env file updated in the root directory. See below:

server side validation in codeigniter 4

  1. Update config file (app/Config/App.php)

    Below is a section of App.php, set $baseURL and $index Page as given below:

  2. Update database setup file (app/Config/Database.php)

    As I mentioned before, I am using a database named 'demo' in localhost with user 'root', so below is our database connection setup in Database.php. Update $default as below:

  3. Update Routes file (app/Config/Routes.php)

    In Routes.php change default controller as Candidate and define the routes for registration form.

  4. Update .env to set the environment

    We need to set the environment to development in the environment (.env) file. This file is in root directory.

    callback validation in codeigniter 4

    If you have not already copied env file to .env file, make a copy of env to .env. Open .env file in notepad and go to the line containing "# CI_ENVIRONMENT = production". Now copy this line and paste it as next line, then update the environment from production to development and remove # from the beginning of the line. See below:

Test the Application

You can test the application using built-in PHP server or you can use Apache web server if you are using xampp.

Test using PHP built-in server

Open command prompt and go to your CI4 project root. In my case it is D:/projects/form. Then type php spark serve and enter. This will start the server in port 8080.

custom validation codeigniter 4

Now open the browser and run http://localhost:8080/. This will open the home page.

validation error in codeigniter 4

Test the validation for all the fields. Just try to submit incomplete form. Also test the invalid email id format and try to register with the same email id which is already registered before. You should see the proper validation messages. Also check the validation for age. You should test all kinds of validations used in the controller methods.

Test using Apache web server

If you are using XAMPP make sure your root folder is xampp/htdocs/form, i.e., you have to install CI4 in this folder. Open httpd-vhosts.conf file in notepad from xampp\apache\conf\extra folder.

Open the file in notepad and add below line at the end of it.

DocumentRoot "D:/xampp/htdocs/form/public"

email validation in ci4

Save it and restart the Apache service from xampp controller.

Now in app/Config/App.php, update base url as below:

Open the browser and run http://localhost. You will see the page as displayed below:

custom validation codeigniter 4

Do the same testing described above.

That's it! Our development and testing are done for this CodeIgniter4 application. Hope you could successfully develop and test it.

download sourde code for form validation in CodeIgniter 4Download Code

I have put the codes for controller, model and view in a zip file. You can download it by clicking on the Download button below. You do not need to register yourself to download it. You can use the code as is or you can modify them as per your requirements.

Custom Validation Rule in CodeIgniter 4Conclusion

Form validation is an important part for any project development. We must ensure that correct and only desired data are stored in the system. Hope this gives you a starting point for form validation in CodeIgniter4.