Changing Default Error Delimiters in CodeIgniter

One thing that I end up doing in almost every CodeIgniter project is changing the default error delimiters from a plain ol’ paragraph

<p></p>

to a fancy shmancy paragraph with an error class on it

<p class="error"></p>

Not a big deal, but I always want a CSS hook for styling my form errors. There are two ways I used to handle this:

  1. Set error delimiters on an as-needed basis in my controller, but that resulted in a lot of code duplication and calling set_error_delimiters() all over the place.
  2. Set error delimiters in the construct of a base controller. It always annoyed me that there wasn’t a config option or something for this and that I still had to put this in a controller and call it on every request.

My Current Solution

One day I was looking through the form validation library and I realized that the error prefix and suffix are set as private variables for the class so I could override them if I extend the form validation library. I just created a MY_Form_validation.php file and dropped it into application/libraries with the following code overriding the default delimiters.

class MY_Form_validation extends CI_Form_validation {

    public function __construct()
    {
        parent::__construct();

        $this->_error_prefix = '<p class="error">';
        $this->_error_suffix = '</p>';
    }
}
  • iamyurie

    Thanks a lot!!