3 tricks with CI Post & Form Validation

Code Igniter is well-known for its great documentation, but sometimes really great features get lost among the code examples. Here are three little tricks that might make life a little easier

To return all POST items and pass them through the XSS filter set the first parameter NULL while setting the second parameter to boolean

In short,

$fields = $this->input->post(NULL, TRUE);

will allow you to grab the entire $_POST and cleanse your data for use, without having to do each one.

Use the Form Validation library to test any variables

A "double trick" here, if you like: First, the Form Validation internally reads and works with the $_POST array, so simply writing:

        $_POST['required_var'] = '';
        $this->form_validation->set_rules('required_var', 'Required Var', 'required');
		if ($this->form_validation->run() == FALSE)
		{
			echo validation_errors();
		}
        unset($_POST['required_var']);

while a bit of a hack, works perfectly fine. Also remember, the Form Validation Library is...just a library. Go ahead and borrow its functions for anywhere you like, which you can read in the system/libraries directory:

        if (!$this->form_validation->valid_email('test'))
        {
        	echo 'Not a valid email';
        }

You can also process the form data that is passed to your callback and return it. If your callback returns anything other than a boolean TRUE/FALSE it is assumed that the data is your newly processed form data.

In other words, writing a callback such as:

	public function username_check($str)
	{
             return json_encode(array('data'=>'lots of additional data I looked up in my db'))
	}

will, instead of simply passing or failing a test, allow you to fully manipulate the data and pass it back to your controller function. (As a real-life example, on a recent project I needed to hit the database to check if a given airport code was valid before insert, but also wanted to insert some denormalized data about that airport at the same time. Since I was hitting the database anyway, I passed back the whole row of info I wanted & processed it for the insert.)

So...read those bits of fine print! There are some gems in there.

Hope that helps.

Contact me