Creating a CodeIgniter App (Part 7): Validation

I decided to continue with the series about CodeIgniter, but now I’ll be writing about more specific topics. In this part, I’ll explain how to use the form_validation library to validate form and ensure the correct data reach the database. Even though it’s an specific topic, I’m going to continue using the same application from previous posts.

Introduction

The idea about the validation came from a comment in the previous post (in the Portuguese post). Validations are not new of course and in fact is necessary and common to ensure the data is correct. I haven’t done it previously because this system was only for advanced users, so even with wrong/empty entries you could remove them from the database without any issues.

But, in order to ensure the integrity of the database, I did the update according to the comment. It’s a simple update, so I’ll explain it just for the users maintenance. I’ll explain as well how the validation library works.

Users Maintenance

In the users maintenance there is a controller called user.php, where we have the index(), add(), edit(), remove() and save() methods. In order to validate entries we need to update only where we save the information in the database. The validation happens before saving the data, of course, and we can use the validation library not only to validate, bu also to prepare the data. It’s possible to use PHP’s function strip_tags to remove HTML tags, for example.

So, the only method we need to update is save(). Before, the method was like this:

    public function save()
    {
        $this->load->model('user_model');

        $sql_data = array(
            'email'    => $this->input->post('email'),
            'level'    => $this->input->post('level')
        );

        if($this->input->post('reset_password')){
            $sql_data['password'] = $this->input->post('password');
        }

        if ($this->input->post('id'))
            $this->user_model->update($this->input->post('id'),$sql_data);
        else
            $this->user_model->create($sql_data);

        redirect('user');
    }

In order to use the validation library we have to load it. To do that, simply add $this->load->library(‘form_validation’). This library allows us to define rules for each field. After defining the rules, we run the validation with $this->form_validation->run(). This method will return FALSE if it finds any errors.

This is the code, with the explanation coming later.

    public function save()
    {
        if($this->input->post('cancel') !== FALSE)
            redirect('user');

        $user_id = $this->input->post('id');

        $this->load->library('form_validation');

        $this->form_validation->set_rules('email', 'Email', 'trim|required|valid_email');
        $this->form_validation->set_rules('password', 'Password', 'trim|required');
        $this->form_validation->set_rules('level', 'Level', 'required');

        if($this->form_validation->run() === false)  {
            $this->error = true;

            if ($user_id)
                $this->edit ($user_id);
            else
                $this->add ();

            return;
        }

        $this->load->model('user_model');

        $sql_data = array(
            'email'    => $this->input->post('email'),
            'level'    => $this->input->post('level')
        );

        if($this->input->post('reset_password')){
            $sql_data['password'] = $this->input->post('password');
        }

        if ($user_id)
            $this->user_model->update($user_id,$sql_data);
        else
            $this->user_model->create($sql_data);

        redirect('user');
    }

First, I updated the cancel button for a submit, this way we can check here if the button was clicked and redirect to the ‘user’ controller. After that, we load the validation library and add the rules. The method set_rules accepts three parameters: the field name (from the input), the second is the text the users sees (the label) and, lastly, the rules.

In this case we are creating rules for the email field, using trim, required and valid_email: “trim” will remove blank spaces before and after, “required” means it’s mandatory and “valid_email” checks if it is a valid email. The second rule will ensure the field is not empty. We also create rules for password and level.

We run the validation inside an “if” condition. If it returns FALSE we’ll define the error property and, in case the user_id has been sent, we’ll run the edit() method. Otherwise we will call the add() method. After loading one of these methods, we need a return to stop the save() method execution. As we don’t have the error property in our controller, we need to add it. Do it right after the LEVEL definition.

private $error = false;

This property will be used in the methods edit() and add() to check if the form was valid or not. Le’t add:

        if($this->error)
            $data['error'] = $this->error;

Paste this piece of code inside the methods edit() and add() just before $this->template->show(‘users_add’, $data);. This way we can update our view to display the errors inside the form in case the variable was defined. Open the file application/views/users_add.php. The updated code will look like this:

<?php
// Load Menu
$this->template->menu('users');
?>

<div id="container">

    <?php echo form_open('user/save'); ?>

    <table>
        <tr>
            <td>
                <?php echo form_label('Email *', 'email'); ?>
            </td>
            <td>
                <?php echo form_input('email', set_value('email', $email)); ?>
            </td>
        </tr>
        <tr>
            <td>
                <?php echo form_label('Password', 'password'); ?>
            </td>
            <td>
                <?php if (isset($id)) { ?>
                    <?php echo form_password('password', set_value('password', $password), 'id="password" disabled'); ?>
                    <?php echo form_checkbox('reset_password', 1, false, 'id="reset_password" title="Edit Password"'); ?>
                <?php } else { ?>
                    <?php echo form_password('password', set_value('password', $password), 'id="password"'); ?>
                    <?php echo form_hidden('reset_password', 1); ?>
                <?php } ?>
            </td>
        </tr>
        <tr>
            <td>
                <?php echo form_label('Level', 'level'); ?>
            </td>
            <td>
                <?php echo form_dropdown('level', $level_list, set_value('level', $level)); ?>
            </td>
        </tr>
        <?php if(isset($error)) : ?>
        <tr>
            <td colspan="2" class="error">
                <?php echo validation_errors(); ?>
            </td>
        </tr>
        <?php endif; ?>
        <tr>
                <td colspan="2">
                    <?php if (isset($id)) echo form_hidden('id', $id); ?>
                    <div class="form-save-buttons">
                        <?php echo form_submit('save', 'Save', 'class="btn-blue"'); ?>
                        <?php echo form_submit('cancel', 'Cancel', 'class="btn-blue"');; ?>
                    </div>
                </td>
        </tr>
    </table>

    <?php echo form_close(); ?>

</div>

Basically that’s what we need to use this library. Something you need to pay attention to:

If you use the set_value function to fill the field value automatically when there are errors in the validation, you need to define a rule for every field, otherwise the function will not find the value. This happens because the function checks if there is an existing validation object ($this->form_validation), if it exists it will return the field values from this object instead of the $_POST variable. Tos olve this problem, even if a field does not need any validation, you can set an empty rule like $this->form_validation->set_rules(‘field’, ‘Field’, ”).

I did similar implementations for the projects and tasks – you’ll find it in GitHub version 1.3.4. Now I’ll explain some other library options.

Library Options

This library offers several validation rules. All of them are well explained in the official CodeIgniter documentation, so I’ll just reproduce it here.

Rules

List of rules that can be applied:

  • required: Returns FALSE if the field is empty.
  • matches: Returns FALSE if the form element does not match the one in the parameter. Usage: matches[form_item]
  • is_unique: Returns FALSE if the form element is not unique to the table and field name in the parameter. Usage: is_unique[table.field]
  • min_length: Returns FALSE if the form element is shorter then the parameter value. Usage: min_length[6]
  • max_length: Returns FALSE if the form element is longer then the parameter value. Usage: max_length[12]
  • exact_length: Returns FALSE if the form element is not exactly the parameter value. Usage: exact_length[8]
  • greater_than: Returns FALSE if the form element is less than the parameter value or not numeric. Usage: greater_than[8]
  • less_than: Returns FALSE if the form element is greater than the parameter value or not numeric. Usage: less_than[8]
  • alpha: Returns FALSE if the form element contains anything other than alphabetical characters.
  • alpha_numeric: Returns FALSE if the form element contains anything other than alpha-numeric characters.
  • alpha_dash: Returns FALSE if the form element contains anything other than alpha-numeric characters, underscores or dashes.
  • numeric: Returns FALSE if the form element contains anything other than numeric characters.
  • integer: Returns FALSE if the form element contains anything other than an integer.
  • decimal: Returns FALSE if the form element is not exactly the parameter value.
  • is_natural: Returns FALSE if the form element contains anything other than a natural number: 0, 1, 2, 3, etc.
  • is_natural_no_zero: Returns FALSE if the form element contains anything other than a natural number, but not zero: 1, 2, 3, etc.
  • valid_email: Returns FALSE if the form element does not contain a valid email address.
  • valid_emails: Returns FALSE if any value provided in a comma separated list is not a valid email.
  • valid_ip: Returns FALSE if the supplied IP is not valid. Accepts an optional parameter of “IPv4” or “IPv6” to specify an IP format.
  • valid_base64: Returns FALSE if the supplied string contains anything other than valid Base64 characters.

Prepping

The library can prepare the fields for you as well. You can use any native PHP function. You just need to pass it as a rule when using set_rule(). Besides PHP functions, CodeIgniter also offers:

  • xss_clean: Runs the data through the XSS filtering function, described in the Input Class page.
  • prep_for_form: Converts special characters so that HTML data can be shown in a form field without breaking it.
  • prep_url: Adds “http://” to URLs if missing.
  • strip_image_tags: Strips the HTML from image tags leaving the raw URL.
  • encode_php_tags: Converts PHP tags to entities.

Creating your own Rules

CodeIgniter allows you to create you own rules using callbacks. All you need to do is create a public method in the same class where you are doing the validation and add the the method name pre-appended with a ‘callback’ as a rule in set_rule(). Example:

When creating the rule:

$this->form_validation->set_rules('username', 'Username', 'callback_username_check');

Add the method:

public function username_check($str)
{
    if ($str == 'test')
    {
        $this->form_validation->set_message('username_check', 'The %s field can not be the word "test"');
        return FALSE;
    }
    else
    {
        return TRUE;
    }
}

The rule callback_username_check will execute the method and will return FALSE if the field is equal to ‘test’. This next method is a practicle example that I use to validate mandatory files:

    public function required_file($str, $field)
    {
        if (!isset($_FILES[$field]) || $_FILES[$field]['name'] == '')
        {
            $this->form_validation->set_message('required_file', lang('home_error_required_file'));
            return FALSE;
        }
        else
        {
            return TRUE;
        }
    }

Conclusion

In this article I showed how to use the validation library from CodeIgniter. This functionality is one of the most useful ones because it ensures that the input are correct. I created a tag with the code as it is right no, so you can easily download it. It is the tag 1.3.4, taht can be downloaded through the link https://github.com/oscardias/Simple-Task-Board/archive/v1.3.4.zip.

oscardias/Simple-Task-Board - GitHub
Contribute to Simple-Task-Board development by creating an account on GitHub.


  • martin

    how to add email functionality for verification? thanks

    • Whad do you mean exactly? Validating emails? Should be like this:
      $this->form_validation->set_rules(’email’, ‘Email’, ‘valid_email’);

  • Zimmermann Jean-Paul

    I’ll check this.
    It seems to be a great great job.
    Thanks a lot

  • mildred collantes

    My program (which is from your previous tutorials) is already okay but when I added your validation codes, it displayed nothing. Help!