Inspired by Hasin Hayder’s separation of ActiveRecord here; i always wanted to separate some other cool stuffs from CodeIgniter so that i could use those in some other projects which are not built using CodeIgniter. One of the attractive libraries of CodeIgniter which i wanted to separate was Validation Library. Especially for its custom callback functions and individual element error calling like $this->validation->fname_error. This helped me to give my clients more accessibility.
Step by step i will try to separate some other cool stuff ( I hope Derek Allard wont’ mind
). Here is my first contribution :
To separate the validation library first take out the Validation.php file from CodeIgniter’s system/libraries folder. BTB i am using CodeIgniter 1.6.1 . Now modify by function names:
- strip_image_tags() – Comment the body content of this function. I did not able to track it’s use.
- valid_ip() – Replace the body of this function from Input library ’s valid_ip() in system/libraries folder.
- xss_clean() – Same as task 2
- CI_Validation() – Comment the whole body
- Run()
For Task 5:
This is where i had to do maximum modification.
First: To eliminate the language pack dependency i commented line Number : 189 containing ‘$this->CI->lang->load(‘validation’);’. Now to be able to find the language strings i have added the following array in the class from ’system\language\english\validation_lang.php’.
var $lang = array(‘required’ => “The %s field is required.”,
‘isset’ => “The %s field must have a value.”,
…….
…….
‘matches’ => “The %s field does not match the %s field.”,
);
In line : 221; i changed ‘$this->CI->lang->line('isset')‘ => ‘$this->lang['isset']‘
In line: 319: i changed ‘$this->CI->lang->line($rule)‘ => ‘$this->lang[$rule]‘
Second: Now the tricky one. Using the Callback functions. For this i commented line 278-281. Actually i did not know what to do with these lines that’s why i commented them
. Now change the line 282 containing ‘$result = $this->CI->$rule($_POST[$field], $param); ‘ to ‘$result = $rule($_POST[$field], $this); ‘.
Now the structure of the callback function:
function abc_check($str, &$validClass)
{
if ($str == ‘abc’)
{
$validClass->set_message(‘abc_check’, ‘The %s field can not be the word “abc”‘);
return FALSE;
}
else
{
return TRUE;
}
}
That’s all for the validation function. Oh.. now to use this class u have to do is :
require_once("Validation.php");$valid = new CI_Validation();
$rules = array(‘fname’ => ‘required|callback_abc_check’,
);
$fields = array(
‘fname’ => ‘First Name’,
);
$valid->set_rules( $rules );
$valid->set_fields( $fields );
if( $valid->run() == false )
echo $valid->error_string;