Skip to content

How to load form validation rules from a database

Derek Jones edited this page Jul 5, 2012 · 5 revisions

Sometimes I would rather load my form validation rules from a database, instead of from a config file, or hard coding them into the controller. This is a short tutorial on how to do that.

First thing to do is add a database table like so:

CREATE TABLE form_validation (
pk_form_validation_id INT(10) UNSIGNED NOT NULL AUTO_INCREMENT,
form_key VARCHAR(20) DEFAULT NULL,
field VARCHAR(50) DEFAULT NULL,
title VARCHAR(50) DEFAULT NULL,
rules TEXT,
PRIMARY KEY (pk_form_validation_id)
);

Then create a MY_Form_validation.php file in system/application/libraries. Paste the following code into that file:

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

class MY_Form_validation extends CI_Form_validation {

/**
 * Checks to see if we need to load rules from the database,
 * then runs the CI_Form_validation library's run method.
 *
 * @access    public
 * @param    string
 * @return
 */

function run($group = '')
{
    // Is there a validation rule for the particular URI being accessed?
    $uri = ($group == '') ? trim($this->CI->uri->ruri_string(), '/') : $group;

    if ($uri != '' AND !isset($this->_config_rules[$uri]))
    {
        $this->load_rules_from_database($uri);
    }

    return parent::run($group);
}

/**
 * Loads rules from a database for a given form key
 *
 * @access    public
 * @param    string
 * @return    
 */

function load_rules_from_database($form_key)
{
    $this->CI->load->database();
    $qry = $this->CI->db->get_where('form_validation',         
            array('form_key'=>$form_key)); 

    foreach ($qry->result() as $row)
    {
        $this->set_rules($row->field, $row->title, $row->rules);
    }
}

}

?>

Then if you were going to make a contact form, you could put the following rows into your table: INSERT INTO form_validation (form_key, field, title, rules) VALUES ("contact", "name", "Your Name", "required"); INSERT INTO form_validation (form_key, field, title, rules) VALUES ("contact", "phone", "Phone Number", "required");

Then in your Controller, you call the form validation run method just as you would if you put the rules into a config file:

$this->form_validation->run('contact') == FALSE

Clone this wiki locally