In this tutorial, you will learn:

HTML Form Structure
CodeIgniter Form Helper
CodeIgniter Form Example Form Validation in CodeIgniter Adding Form Validation Rules
Displaying Form Validation Error Messages
Populating Submitted Form Data: Sticky Forms
CodeIgniter Form Validation Example

HTML Form Structure

The following code shows the structure of a typical HTML form. HERE,

are the opening and closing tags of the form. The id and name attribute specify the name and id of the form. The method attribute specifies the HTTP Verb to be used. This is usually specified by POST verb Specifies the form elements. The name attribute is the variable name that is submitted to the backend server for processing.

CodeIgniter Form Helper

HTML is great is easy to understand and write, but CodeIgniter makes things even simpler. CodeIgniter has built-in functions to create HTML forms. Let’s consider the following CodeIgniter form submit code that uses the form helper to create a form HERE,

echo form_open(‘create_user.php’, [‘id’ => ‘frmUsers’]); creates the form’s opening tag, sets the action to POST Verb and sets the action URL to create_user.php echo form_label(‘User Id’, ‘user_id’); creates a label that reads User Id for the input field with the name of user_id. echo form_input([‘name’ => ‘user_id’]); creates an input field of text type with the name of user_id echo form_submit(‘btnSubmit’, ‘Create User’); creates a submit button with the label of Create User echo form_close(); closes the form

As you can see from the above CodeIgniter code, form helpers make it easy for us to create forms using pure PHP. By passing attributes to the form helper methods, we can customize the HTML that is generated for the form. The above code generates the following HTML form code The biggest advantages of using the form helper is that it generates semantically correct code that adheres to the set HTML standards. You can refer to the official CodeIgniter documentation for more details https://codeigniter.com/user_guide/helpers/form_helper.html

CodeIgniter Form Example

After covering the basics of CodeIgniter, let’s get back to our tutorial project which we have been working on throughout this CodeIgniter Tutorial Series. In summary, the tutorial project builds a contacts management app that will store the details in the database.

Create Contact

in the previous tutorial, we created routes for our applications and simple views. Open application/views/contacts/create.php Modify the code for create.php as follows Note: the above code uses plain HTML to create forms. Let’s now see how our forms look like in the web browser Load the following URL into our web browser. http://localhost:3000/contacts/create If you have been creating the tutorial project, then you should be able to see the following

Form Validation in CodeIgniter

Validation plays a very critical role when processing data from forms. Let’s say a user is signing up on a website; we want to make sure that they fill in their required details and email address. We need to make sure that the email address that has been entered is valid. If we are working with date values, then we want to make sure the date ranges are valid. We wouldn’t have to accept a date that has 32 days in a month etc. Validation solves the above problems. CodeIgniter Validation is done on two (2) fronts when working with web applications. Client-side validation is done on the part of the web browser. This usually involves the use of HTML and JavaScript. Client-side validation improves performance as everything is done at the client-side. So, there is no need to submit the data to the server. The disadvantage of client-side validation is the user has control over it. If you rely on JavaScript to validate and the user disables JavaScript in the browser, then your validation will fail. Server-side validation is done on the server-side. The downside of this validation is the user has to submit the data to the server for processing and wait for the response. This uses up network resources and may degrade the performance. The major advantage of server-side validation is you have greater control and you are assured of your validation rules working even if the user disables JavaScript in the browser. A better strategy is to use client-side as the primary validation strategy and server-side as a fallback mechanism.

Adding Form Validation Rules

CodeIgniter has a built-in validation library. The library is loaded using the following line The CodeIgniter form validation library can be used to perform some of the following actions

Check for required fields. This examines the submitted values and returns an error if a field that has been tagged as required does not have a value Data type validation – some fields may require numeric values only. If a non-numeric value is detected, then the library returns an error. Execution of the form submission is also aborted. Length validation – some data types require fields to have a certain minimum or a maximum number of characters. The validation library comes in handy in such cases. Data sanitization – the validation library also has capabilities that remove malicious code from the submitted data for security reasons. If for example, the submitted values have active JavaScript or SQL Injection code in them, the validation library strips away the harmful code and renders it useless. Validate unique database fields – suppose you have a form where users sign up using an email address. You would want to ensure that the email address is unique. The library makes it easy for you to check the submitted data against a database table and field. This allows you to know that the value has already been taken up.

Validation rules are set using the following format HERE,

‘field’ specified the form field name to be validated by the library ‘human readable field’ specifies the human-readable format of the field under validation. This is displayed back to the user when an error occurs. ‘rule’ specifies the validation rule to be applied such as required, numeric, check if minimum length is… etc. [‘custom message’] is optional and can be used to set a custom validation message that should be displayed when the validation rule fails.

Following is a form submit in CodeIgniter example for validating the contact name HERE,

The above code checks if the field contact_number has been entered. If it is not set then returns an error that says Contact Number field is required.

To run the validation against the set rules, we use the following function of the validation library If the above code returns false, then one or more set rules have failed. If it returns true, then the validation rules have all passed, and you may proceed with further action. Let’s look at more examples of validation rules. Suppose you want to validation some fields say the contact name, number and email address, you can use the following code to accomplish that. HERE,

In the above email validation in CodeIgniter example, we provide an array of fields with rules for the set_rules function of the library. This makes it easier when you are validating some fields.

Unique Validation

If we want to validate the contact number to ensure that we do not save the same number twice, we can use the following rule to do that. HERE,

| is used to pipe multiple rules together is_unique[contacts.contact_number] checks if the value for contact_number is unique against the contact_number field values in the database table contacts.

Displaying Form Validation Error Messages

If an error occurs during the processing of the form, you can use the following code to display the validation errors that occurred HERE,

The above function returns all the errors that occurred.

Populating Submitted Form Data: Sticky Forms

Some forms have many fields, and if an error has occurred, then you want to make sure that the data that was added correctly is preserved. The validation library has mechanisms for accomplishing that. We do that by using the following code. HERE,

The above code displays that input that the user had entered.

For a complete reference guide on the methods that are available under the validation library, you can refer to the API documentation from the official user guide for CodeIgniter https://codeigniter.com/userguide3/libraries/form_validation.html

CodeIgniter Form Validation Example

Throughout these tutorial series, we have been adding more code to our tutorial project which is a contacts management application. In this section, we will load the validation library and see how we can put it to practical use using a real-world example application. Modify the routes code as follows to include the store method Let’s now load the form validation library in the Contacts controller and set some validation rules. Modify the code as shown in the below form validation in CodeIgniter example: HERE,

$rules = array(…) sets defines the validation rules $this->form_validation->set_rules($rules); sets the validation rules if ($this->form_validation->run() == FALSE) {…} runs the validation rules and if they fail the form is redisplayed with validation errors. If the validation passes, we are simply redirecting to the list contacts page. Under normal circumstances we would write the data to the database. We will do that in the next tutorials when we look at databases.

Modify the create view in application/contacts/create.php code as shown in the below form validation CodeIgniter example: HERE,

we display the errors that occur if any during the validation process sets the value that was previously set if any

You need to load the following URL into your web browser. Then click on Create Contact without entering any values

Summary

Forms provide a way for users to interact with the application and submit data. HTML is great is easy to understand and write, but CodeIgniter makes things even simpler. CodeIgniter has built-in functions to create HTML forms. Validation plays a very critical role when processing data from forms. In this tutorial, we have seen major validation strategies and their pros and cons. We also learned how- to set validation rules and out error messages using CodeIgniter’s built-in validation library. We have ended the lesson by implementing the knowledge gained in a practical application.