Brenelz Web Design Solutions

Web programming, the brenelz way!

Brenelz's Web Development Tips


PHP CodeIgniter Validation

Most web developers shudder when the task of validation comes up.  This is if you spend the time to validate your user input.  I remember back in university when our professor (Chris Brown) made us pseudo code out what we were trying to accomplish with our application.  You know what task came up multiple times during our discussions?  Well you guessed it, Validation.  Personally validation is not one of my favorite parts of making a website.  It can be tedious, and a lot of the time developers skip it.

Well I encourage you not to skip it and will show you what kind of functionality CodeIgniter comes with.  I assume you have CodeIgniter installed on your server.  Please visit the installation guide if you haven’t.  As well I have created a database and configured CodeIgniter to connect to it.  I have one table called categories with two fields of categoryID, and title.  Put some dummy information for the purposes of this demo.

Next, lets create a simple controller called “Form” in our system/application/controllers directory.

< ?php
class Form extends Controller
{
    function __construct()
    {
        parent::Controller();
        $this->load->helper(array('form', 'url'));
        $this->load->library('validation');
        $this->load->database();
    }
    function index()
    {
        $query = $this->db->get('categories');
        foreach ($query->result() as $category)
        {
            $data['categories'][] = $category->title;
        }
        $this->load->view('form', $data);
    }
}
?>

In the above code we have loaded some helpers, libraries, and connected to our database.  Our validation library is where our validation code comes from.   In our index function we get all our categories from the database.

The next step is to create a couple views.  One containing the form we wish to validate and another that will be shown when our form is submitted successfully.  Create the following two files in the system/application/views directory.

form.php

<html>
    <head>
        <title>CodeIgniter Validation</title>
    </head>
    <body>
        < ?php echo form_open(form/index'); ?>
            <h5>Title</h5>
            <input type="text" name="title" value="" size="50" />
            <h5>Email</h5>
            <input type="text" name="email" value="" size="50" />
            <h5>Category</h5>
            < ?php echo form_dropdown('categoryID', $categories); ?>
            <h5>Description</h5>
            <textarea name="description" cols="40" rows="5"></textarea>
            <div><input type="submit" value="Submit" /></div>
    </body>
</html>

success.php

<html>
    <head>
        <title>Success - CodeIgniter Validation</title>
    </head>
    <body>
        <h3>Your form was successfully submitted!</h3>
        <p>< ?php echo anchor('form/index', 'Try it again!'); ?></p>
    </body>
</html>

Now take a look at what we have so far in your browser window at index.php/form/index.  We should see the form that we have created above.  Its action is pointed to our form controller and the index function.  The other slightly difficult part of the form.php is the dropdown.  We have used a function of the form helper that we have loaded earlier.  form_dropdown takes three arguments; the first is the name of the <select>; second is the array that contains the data; and the third argument is which <option> you want selected.  We will use this a little later on.

You should see the current problem we have with our form.  We can click submit without filling in any fields.  This is a big problem as we would never want to allow the user to do this.  This is where we need to change our above index function.

function index()
{
    $rules['title'] = "required|min_length[5]|max_length[25]";
    $rules['description'] = "required";
    $rules['email'] = "required|valid_email";
    $this->validation->set_rules($rules);
    if ($this->validation->run() == FALSE)
    {
        $query = $this->db->get('categories');
        foreach ($query->result() as $category)
        {
            $data['categories'][] = $category->title;
        }
        $this->load->view('contact', $data);
    }
    else
    {
        $this->load->view('success');
    }
}

Now, don’t get too frightened by the new code; it is fairly self-explanatory.  We have set rules for each of our fields.  The array key for the $rules variable is the same as our field name on the form.  Then we assign it a set of attributes.  For example the field with a name of ‘title’ is required, has a minimum length of 5 and a max length of 25.  Our email field is required and is checked to be a valid email.  We apply these rules to our validation with the $this->validation->set_rules($result) line.

Lastly we run our validation and load different views based on whether our validation passes or not.  One thing we are still missing is to add the following line under our form.php body tag.


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

This is what actually prints out our error messages.  If we didn’t add this the user would not know what fields are wrong.

There is a lot more I could show you with the validation class but I will leave it at this for now.


3 Comments

  1. Marc
    Posted October 17, 2008 at 4:01 pm | Permalink

    Just one word: code indentation….

    what the heck happened to your tabs or spaces?

  2. Posted October 17, 2008 at 4:13 pm | Permalink

    The indentation should be better now. Takes away all my indenting when I save it.

  3. C
    Posted November 21, 2008 at 5:54 am | Permalink

    “Just one word: code indentation….”
    Looks like 2 to me…

    Thanks for the article admin

Post a Comment

Your email is never shared. Required fields are marked *

*
*

Copyright © 2008 Brenelz Web Solutions.

Winnipeg Web Development by Brenelz Web Design Solutions Logo Brenelz Web Solutions