CodeIgniter - Custom errors using the Form Validation class

< Back to blog | Add a comment

Posted: 4th Mar 2009
Categories: Web Development
Tags: codeigniter mvc error handling validation web development coding php

TECHY WARNING - This post has techy-talk, be warned

Recently I've been using the new Form Validation Class on CodeIgniter and though overall it is much better than the previous validation class I found a gripe with it recently when trying to add custom error messages using the "validation_errors()" helper.

I like to put the "echo validation_errors()" helper in my view files inside an error DIV, but only show the DIV if the Form Validation class returns errors. But what if you have a function in your model or controller that might fail for a reason outside of the Form Validation call and you want to set a global message (which shows up when you call the validation_errors() helper). Previously you were able to just set the error message by overriding the error_string variable in the class, now things are a bit different.

For example. Recently we've been building a CSV import feature for a client. If the CSV (comma separated values) file is badly formatted it returns the function FALSE and then in the controller we let the view file know there was an error. But because we are using the Form Validation class for other fields in the form we don't want to have yet another IF statement in the view file for an error message set by the failed CSV import function. We want to ideally use the validation_errors() helper to show our CSV import error message.

So, with the new Form Validation class in CodeIgniter we know that errors are now set in to an array called _error_array. So all we need to do is add a new error message to that array, so if our CSV import function fails we can show that error message along with other errors that might show up from the Form Validation checking.

It is really easy, and below is the code. Remember you will need to make a file called MY_Form_validation.php and save that in your libraries folder.

<?php if (!defined('BASEPATH')) exit('No direct script access allowed');

/**
 * MY_Form_validation Class
 *
 * Extends Form_Validation library
 *
 * Allows for custom error messages to be added to the error array
 *
 * Note that this update should be used with the
 * form_validation library introduced in CI 1.7.0
 */
class MY_Form_validation extends CI_Form_validation {

    function My_Form_validation()
    {
        parent::CI_Form_validation();
    }

    // --------------------------------------------------------------------

    /**
     * Set Error
     *
     * @access  public
     * @param   string
     * @return  bool
    */  

    function set_error($error = '')
    {
        if (empty($error))
        {
            return FALSE;
        }
        else
        {
            $CI =& get_instance();

            $CI->form_validation->_error_array['custom_error'] = $error;

            return TRUE;
        }
    }

}

?>

Then you would call the function with:

$this->form_validation->set_error('There was a problem with the CSV import, please try another file');

Tags / Keywords: codeigniter, mvc, error handling, validation, web development, coding, php

Comments

By Adi on 13th Mar 2009

thanks for the snippet! I was just about doing the same thing when I saw your post at the CI forum :)

By Stu Green on 13th Mar 2009

Hey Adi thanks, I would read your blog but unfortunately it's all in a different language!

By tyu on 3rd Sep 2009

Being a freshman in blogging, I really appreciate such resources where people write constructive posts about useful things in a good understandable manner. I've already found quite a lot of interesting articles by http://rapid4me.com rapidshare search engine. Thanks God, I've also found your blog.

By Stu Green on 3rd Sep 2009

Thank you tyu, that is very kind of you to say!

By Adam Lynam on 30th Sep 2009

Hey Stu, very nice extension to CI validation, has allowed me to keep in the spirit of CI and maintain code flexibility!

Thanks.

By Ivan Kristianto on 11th Nov 2009

Hi,
i found that your snippet is really great.
But i have a fix a little in the constructor, it is better lije this:

function My_Form_validation($config = '')
{
parent::CI_Form_validation($config);
}


so if you have a Validation Rules in a Config File, it will perfect.
Thanks.
Ivan

Add a comment









Back to top