Quantcast
Channel: Brettic.us » CodeIgniter
Viewing all articles
Browse latest Browse all 4

CodeIgniter Form Validation: How to allow inline and config rules simultaneously

$
0
0
CodeIgniter

CodeIgniter Form Validation

Continually using the CodeIgniter MVC Framework has allowed me to experience many of it’s numerous “pros.” However, some times, I also hit a snag with one or more of it’s infrequent ”cons.”  Truthfully, it’s put together overwhelmingly well (and much credit is due to the Ellis Labs crew for helping to make a PHP developer’s life a little easier.) Unfortunately, some libraries just do not work the way one (okay, me!) would expect them to work. Perhaps they are just a bit too inflexible for me. For example, I’ve never been a huge fan of CodeIgniter’s Form Validation library, and now I have yet another reason to scorn it somewhat. Admittedly, I’m probably being a bit too severe on this one. However, I feel annoyed in situations where lack of proper documentation costs me precious time (I say this in light of CodeIgniter’s, otherwise, excellent documentation.) Luckily, my perceived notion of how CodeIgniter’s  Form Validation Library should work can be accomplished, once again, with the kind of simple modification that keeps me coming back to CodeIgniter time and again.

The problem

After using a 3rd party library for CAPTCHA’s today, I noticed that the rules in the included application/config/form_validation.php file (hereby referred to as the “config file”) were not running. My other rules that I had defined inline (inside the controller) were working, but it seemed to ignore the rules in the config file completely. When I looked into the the form validation core library, I noticed that when rules are set from within the config file, they are only evaluated if no rules were set inline (set via $this->form_validation->set_rules(…)…) In other words, you must set no rules inline if you want your config file rules to work. This behavior took me off guard a bit because I could not see it documented in the manual (if anyone feels the need to enlighten me, please do.) Also, it makes importing 3rd party code in this manner potentially confusing (I have never used the config file approach before.) I decided that it made more sense to be able to use both types of rules simultaneously. Thus, I wrote an extended version of the Form Validation library.

The Code

This extended version of the Form Validation library allows me to mix both inline and config rules. If inline rules by the same field name are set, these will override the settings in the config file:

<?php
/**
 * Extension class to override Core Form Validation behavior.
 *
 * @author bretticus
 */
class MY_Form_validation extends CI_Form_validation {
    // --------------------------------------------------------------------
 
    /**
     * Run the Validator
     *
     * This function does all the work.
     *
     * Modified by Brett Millett:
     *  Provided option to remove the config or inline only restriction on
     *  rules. This version will process config rules first and then any
     *  inline rules that exist after. This has the benefit of allowing
     *  inline rules to overwite config rules by the same key.
     *
     * @access	public
     * @return	bool
     */
    function run($group = '', $combine_conf_inline = FALSE) {
        if ($combine_conf_inline) {
            //only perform if we have both field and config rules.
            if (count($this->_field_data) > 0 && count($this->_config_rules) > 0) {
                // 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])) {
                    $config_rules = $this->_config_rules[$uri];
                } else {
                    $config_rules = $this->_config_rules;
                }
 
                // only set the rule if it has not already been set inline.
                foreach ($config_rules as $row) {
                    if (!isset($this->_field_data[$row['field']]))
                        $this->set_rules($row['field'], $row['label'], $row['rules']);
                }
            }
        }
        //run parent version last, so field rules will  override config ones and update
        return parent::run($group);
    }
}
?>

Examples

<?php
 
if (!defined('BASEPATH'))
    exit('No direct script access allowed');
 
$config = array(
    'mycontroller/index' => array(
        array(
            'field' => 'recaptcha_response_field',
            'label' => 'lang:recaptcha_field_name',
            'rules' => 'required|callback__check_captcha'
        )
    )
);

To use both combined, just call run() with an optional 2nd parameter:

class Mycontroller extends Controller{
	function index() {
            $this->load->library('form_validation');
            $this->load->library('recaptcha');
 
            $this->lang->load('recaptcha');
            $data = array();
 
            //get recaptcha html
            $data['recaptcha_html'] = $this->recaptcha->get_html();
 
            $this->form_validation->set_rules('name', 'Your Name', 'trim|required');
 
            // call with new optional 2nd param to combine inline and config file rules.
            if ($this->form_validation->run('', TRUE) === FALSE) {
                $this->load->view('captcha_form', $data);
            } else {
                $this->load->view('captcha_form_success', $data);
            }
        }
}

Viewing all articles
Browse latest Browse all 4

Latest Images

Trending Articles





Latest Images