Validating Web Forms with the Code Igniter PHP Framework

If you’re a web developer, you’ve probably written any number of scripts designed to validate the input entered into a web form. More than likely, then, you’d like something that will make that job easier. Enter the Code Igniter PHP framework. In this fourth part of a nine-part series on this framework, you’ll learn how to use it to do basic validation on a web form.

Introduction

As you know, not all the PHP frameworks available nowadays on the web have been created in the same way. This is particularly relevant when you need to choose one of them with which to start developing several web applications.

For example, Zend is a solid piece of software, best suited to building enterprise-level PHP programs. This means that some of its features can be pretty overwhelming for developers taking their first steps into the huge terrain of object-object programming.

However, among the numerous PHP frameworks that present a friendly learning curve, there’s one that stands from the rest, not only for its remarkable capabilities for developing complex applications in a short time, but for its minimal setup requirements.

Of course, as you might have guessed, I’m talking about Code Igniter (http://codeigniter.com), a software package created with PHP 4 that allows you to build database-driven PHP programs within minutes! No, really.

In the previous tutorial of this series, I demonstrated how to use this framework to develop a simple MySQL-driven application. It was tasked with pulling a few database records from a simple table to be displayed later on the browser.

In addition, it’s worth mentioning that the application in question had the capacity for paging these records across several web documents, thanks to the assistance of the pagination class that comes bundled with Code Igniter.

Now that I have quickly summarized the topics that were discussed in the last tutorial, it’s time to continue exploring the many other useful features offered by Code Igniter. Therefore, in the course of the next few lines, I’m going to show you how to use the validation class included with this framework to develop a PHP program that can be used to check data submitted through some web forms.

Once again, you’ll have opportunity to see for yourself how easy it is to validate online forms with Code Igniter. Let’s get started!

{mospagebreak title=Validating user-supplied data using the MVC pattern}

As I mentioned in the introduction, validating web forms with Code Igniter is actually a no-brainer process that can be tackled by any developer with an intermediate background in the Model-View-Controller pattern.

To be frank, the whole validation procedure is reduced to creating a controller class that checks to see if the data collected with an online form is valid or not, and then shows one of two different views, according to the result of this checking process.

Obviously, the first view will display a successful web page, while the second one will show an error message along with the corresponding web form. Quite simple to understand, right?

However, the best way to grasp how to validate online forms with Code Igniter is simply by showing some functional code. Period. Thus, based on this concept, below I listed the signature of a brand new controller class which performs all the validation steps described previously. Here it is:

class Validator extends Controller {

function Validator(){

// load controller parent

parent::Controller();

// load ‘url’ helper

$this->load->helper(‘url’);

// load ‘form’ helper

$this->load->helper(‘form’);

// load ‘validation’ class

$this->load->library(‘validation’);

}

function index(){

// set validation rules

$rules['firstname']="required";

$rules['lastname']="required";

$rules['email']="required";

$this->validation->set_rules($rules);

// check if form has been submitted properly

if ($this->validation->run()==FALSE){

// redisplay web form

$this->load->view(‘form_view’);

}

// display success web page

else{

$this->load->view(‘success_view’);

}

}

}


It’s hard to believe, but the above “Validator” controller class is almost all the PHP code required to validate a web form. In this specific case, the controller begins loading all of the classes that it’ll need to perform a basic validation on a sample contact form. The form is composed of some typical fields, such as the user’s first and last names, and the email address.

As you can see, the class includes a couple of helper functions, called “url” and “form” respectively. Not surprisingly, these functions are used by Code Igniter to generate dynamic URLs and form parts too. However, these functions will be utilized at a later time, when rendering the corresponding views. Thus, for the moment, pay attention to the following line of code:

$this->load->library(‘validation’);

As with other examples developed earlier, this expression is used to include the validation class, which naturally is utilized to check whether or not the fields of the sample web form have been filled with data. This process can be more clearly understood if you examine the code snippet below:


// set validation rules

$rules['firstname']="required";

$rules['lastname']="required";

$rules['email']="required";

$this->validation->set_rules($rules);

In this concrete situation, the set of checking rules assigned to the validation class are pretty simple actually, since they’ll only verify if the text boxes of the web form aren’t empty. That’s all. However, it’s perfectly possible to specify more strict validation rules, but this topic will be covered in detail in upcoming articles of the series.

Once the controller determines if the web form has been submitted correctly (or not), it’ll redisplay the form, including an error message, or it’ll show a success web page, depending on the result of this validation process. I told you that validating online forms with Code Igniter was really easy! And before I forget, please save this file to the Code Igniter /system/application/controllers/ folder as “validator.php.”

Now that you have hopefully grasped how the previous “Validator” class works, it’s time to see how to create the view file that redisplays the web form when it contains one or more empty fields.

To see how this file will be built, please jump ahead and read the following section.

{mospagebreak title=Displaying error messages when validating an online form}

In the previous section, you learned how to use a controller class to determine what course of action to take, either when the form in question has been submitted correctly, or when it fails to pass the validation process.

Now I’m going to show you how to create the view file that displays the pertinent online form, and incidentally, it also shows an error message as a result of the data checking process.

That being explained, please examine the code below to see how this error view file looks. 

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">

<head>

<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />

<title>Entering user data</title>

<head>

<body>

<h1>Entering user data</h1>

<?php echo $this->validation->error_string;?>

<?php echo form_open(‘validator’);?>

<p>First Name <input type="text" name="firstname" value="" size="50" /></p>

<p>Last Name <input type="text" name="lastname" value="" size="50" /></p>

<p>Email <input type="text" name="email" value="" size="50" /></p>

<p><input type="submit" value="Send Data" /></p>

</form>

</body>

</html>

As shown above, the previous view file is quite simple to follow. As you can see, it’s comprised of a basic online form that contains three text boxes for collecting the user’s first and last names, and the corresponding email address.

However, you should notice two important things regarding the way that the above contact form is created. First, a PHP statement has been included at the beginning of it. As you may guess, this is the error message that will be  generated by the Code Igniter validation class when the web form fails to pass the validation process.

Finally, the view file uses the form helper function loaded previously by the controller to create a <form> opening tag that points exactly to the controller’s location. Naturally, it’s possible to build this tag manually, but using the helper makes sure that the correct URL will always be assigned to the “action” attribute of the online form.

So far. So good. At this stage, I taught you how to build a simple view file for showing a basic error message when validating a specific web form. In addition, the view will redisplay the form in question if any of its fields has been left empty, so users can repopulate the offending fields with the correct data and resubmit it.

So, now that you hopefully learned how the previous view file does its thing, save it to the Code Igniter /system/application/views/ folder, and move on to see how to create the view that displays a primitive successful web page when the pertinent web form is submitted correctly.

To learn the full details for how this brand new view file will be built, please jump ahead to read the next section. 

{mospagebreak title=Building a confirmation view file}

Building a successful web page that shows a confirmation message to the user when the previous contact web form has been submitted correctly is an extremely simple process. You’ll surely grasp it in a snap.

Below I listed the complete signature for this successful view, so you can see clearly how it works. Here it is:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">

<head>

<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />

<title>User data submitted successfully!</title>

</head>

<body>

<h1>User data submitted successfully!</h1>

<p><?php echo anchor(‘validator’,’Go and submit the form again’);?></p>

</form>

</body>

</html>

That was really simple to code and read, wasn’t it? In this particular case, the above view file will display a typical confirmation message once the pertaining web form has been submitted correctly. Of course, the only detail to stress here is the use of the URL helper function loaded previously by the corresponding controller, which dynamically generates an anchor tag that points to the controller’s location, in case a user wants to submit the online form again.

Finally, save this new view file to the Code Igniter /system/application/views/ folder, as you did with in the example developed in the previous section, and test the application by typing into your browser’s address field the following URL:

http://localhost/codeigniter/index.php/validator/

You’ll be amazed at how sweetly the previous example works!

At this point I explained how to build a basic web application that uses the validation class bundled with Code Igniter to check whether or not the fields of a sample web form have been filled. Indeed, you shouldn’t have major problems understanding how this application works, but naturally you can fill some gaps on this topic by examining all of the code samples included in this tutorial.

Final thoughts

In this fourth episode of the series, you hopefully learned how to employ the validation class that comes included with Code Igniter to perform a basic validation on a simple online contact form.

In the forthcoming article, I’m going to show you how to perform strict validation on the data entered into a sample web form. So, now that you’ve been warned of the topics that will be discussed in the next tutorial, you don’t have any excuses to miss it!

[gp-comments width="770" linklove="off" ]

antalya escort bayan antalya escort bayan Antalya escort diyarbakir escort