Part of the EllisLab Network
   
1 of 2
1
Validation Class Extension
Posted: 28 April 2007 03:20 AM   [ Ignore ]  
Grad Student
Rank
Total Posts:  40
Joined  03-29-2006

FILE LINK TO MY_VALIDATION.PHP v1.22:    http://rapidshare.com/files/59154081/MY_Validation.php.html

(This mod is inspired from http://codeigniter.com/forums/viewthread/47350/)

(This post has been edited to reflect recent updates)

Alright, here is my first contribution to the CI community. I wish that the developers would add this modification into the future versions of the framework.

So what is this? Well, as much as I like CI’s validation class, it does have some problems. First, you are limited to a single callback function per rule. I can find no logic behind this constraint so I have fixed this. Now, you can use as many custom callbacks as your heart desires. Second, you have to put ALL your custom callbacks in the calling controller. Why does this suck? If your site has a front (user) and back (admin) end to it, both portions might require using the same custom callback. This forces you to duplicate your callback in ALL the controllers that you want to use it in. Fun fun! I have fixed this. Now, you can create a class file anywhere in your system and put callbacks in it and load it from ANY controller. Third, if you created a custom callback to check if the username+pass match exists in the database, it would cost 1 database hit. Why is this signifigant? Well, all the callback gives you is a TRUE/FALSE at the cost of 1 hit. Thus, if the validation routine returned TRUE, you would still have to requery the database to retrieve the userdata for that username+pass. Well, I have also fixed this. In my class which extends CI_Validation I have a property called $return_data. In any of my custom validation methods, if I need to perform a database query, any return data is no longer wasted because I can simply do “$this->CI->validation->return_data[] = $query_results” to save the results while still returning TRUE/FALSE for validation purposes.

To acomplish all this I had to overwrite the run() method in CI_Validation. Some people argue that I could have simply extended CI_Validation and put my custom callbacks in there. Yes, that is very true. However there is a big disadvantage to that… a site with several modules (ex., authentication, products, categories, etc) would probably require custom validation routines for each of those modules. It sure would get cumbersome and confusing having all those modules validation routines in 1 file… plus, it would inhibit sharing files amongst the CI community. Why? Well if I wanted to download someone’s authentication package, it would come with their MY_Validation.php which I would have to go through and combine with my MY_Validation.php class. This is quite a bother. Thus, having the ability to load a custom validation class located in a ‘validators’ folder in your application directory. So just make a “validators” folder in your app dir and make your validation classes.

Okay, so how do you use my package?

1. Download My_Validation.php and plop it in your libraries folder.

2. Create a validator class in your application/validators folder.
NOTE: The validator classname must be the SAME as the validator filename.
Here is an example:

<?php if (!defined('BASEPATH')) exit('No direct script access permitted.');
/**
* This is how you create a custom validation class.
* As you can see, if the database query returns a result, we store that result
* in the $data array located in the validation object
*
* Also note how this class does not extend any other class. So it is not necessary to
* extend CI_Validation or My_Validation! Just create a class and start making your
* validators!
*/
class Book_Validator{

    
var $CI;

    function
Book_Validator()
    
{
        $this
->CI =& get_instance();
    
}

    
//Checks to see if this username was already found in the database
    
function title_check($title)
    
{
        $query
= $this->CI->bookmodel->getBookByName($title);
        if (
$query->num_rows() > 0)
        
{
            $this
->CI->validation->set_data['book_validator'] = $query->result_array();
            return
TRUE;
        
}

        $this
->CI->validation->set_message('title_check', 'Could not find the specified book in the database!');
        return
FALSE;
    
}
}
?>

3. In your controller, create a rule and insert your validator rule (method) into it (you do not have to add “callback_” onto your method name in the rule anymore).

$rules['title']=trim|required|min_length[5]|max_length[30]|xss_clean|title_check

4. In the controller that you want to validate, right after loading CI’s validation library, simply add ‘$this->validation->add_validator(‘your_validator_filename’);’ You can send it a single validator class name, or an array of validator class names. Here is an example:

$this->load->library('validation');
$this->validation->add_validator('book_validator');

or

$this->load->library('validation');
$this->validation->add_validator(array('book_validator', 'user_validator'));

Tell me if you guys find this useful. I’d love some feedback and I hope the developers add something like this into the next version of CI because being limited to 1 callback in the controller sucks balls.  tongue wink

Profile
 
 
Posted: 28 April 2007 04:23 AM   [ Ignore ]   [ # 1 ]  
Grad Student
Rank
Total Posts:  35
Joined  04-03-2006

Hi Kiger,

Thanks for the contribution, i have been thinking about this same issue for the last week. This a very nice solution to some of the problems i have experienced, and just extended the class to provide the functionality i needed.

Some changes i will probably make to your class :

1. Implementing an addRule() (add_rule() alias to meet coding standards) method to encapsulate the the $this->load->library() and $this->validation->setValidationClassNames()

2. Grouping the validators/rules into their own directory, the libraries directory probably isnt the best place, a ‘validator’ directory would be more concise.

Many thanks for the contribution, certainly got me thinking!

A quick mock up of the changes (NOT TESTED!) :

API

$this->load->library('validation');
$this->validation->addRule('book_validation');

Patch

<?php

class ValidationPatch {

    
var $_instance;
    var
$_rulePath = 'validator';
    
    function
ValidationPatch() {
        $this
->_instance =& get_instance();
    
}

    
/**
     * This will add the rule to the CI singleton to be call by the validation class
     *
     * @param mixed $string
     * @return void
     */

    
function addRule($rule) {

        
// Grab our validator and check it exists

        
if(!is_file(APPPATH . 'validators/' . $rule . EXT)) {
            show_error
('Could not find the validator rule (' . $rule . ') in the ' . $this->_rulePath . ' directory' )
        }
        
        
// Require validation

        
require_once(APPPATH . 'validators/' . $rule . EXT);
        
        
// Add the validator to the singleton instance
        
        
if(!is_object($this->_instance->$rule)) {
            $this
->_instance->$rule = & new $rule();
        
}else{
            show_error
('Could not add validator rule (' . $rule . ') as it has already been declared');
        
}
        
        
// Set the validation rule
        
        
$this->validation->setValidationClassNames($rule);
    
}

    
/**
     * Alias of addRule()
     *
     * @param mixed $string
     * @return void
     */

    
function add_rule($rule) {
        
return addRule($rule);
    
}

}

?>
Profile
 
 
Posted: 28 April 2007 06:07 AM   [ Ignore ]   [ # 2 ]  
Grad Student
Avatar
Rank
Total Posts:  92
Joined  01-29-2007

I haven’t had a chance to test this yet, but it sounds really good!

If it works as your post says, it would be great to get this into the core.

I like andyr’s suggestion of using a “validation” directory instead of the libraries directory.

Profile
 
 
Posted: 28 April 2007 11:23 AM   [ Ignore ]   [ # 3 ]  
Grad Student
Rank
Total Posts:  40
Joined  03-29-2006

@andyr

Question about your class. When you said “coding standards”, where did you get the standards from? I am trying to code the best way possible, so if there is a place or book that you got them from then I would be interested in learning about it.

And as for adding a directory for validators, I gave it some thought and yes, that’s probably the best idea instead of just letting each user to do whatever, however I think you got confused in your patch class. We will have individual validators (classes) and those validators will have rules (methods). So the add_rule should instead be called add_validator and some of the other code will have to be changed.

I have updated the code in the original link in my first post. Tell me if you think it acomplishes what you were talking about.

Profile
 
 
Posted: 29 April 2007 05:51 PM   [ Ignore ]   [ # 4 ]  
Grad Student
Rank
Total Posts:  35
Joined  04-03-2006
kiger - 28 April 2007 11:23 AM

@andyr

Question about your class. When you said “coding standards”, where did you get the standards from? I am trying to code the best way possible, so if there is a place or book that you got them from then I would be interested in learning about it.

And as for adding a directory for validators, I gave it some thought and yes, that’s probably the best idea instead of just letting each user to do whatever, however I think you got confused in your patch class. We will have individual validators (classes) and those validators will have rules (methods). So the add_rule should instead be called add_validator and some of the other code will have to be changed.

I have updated the code in the original link in my first post. Tell me if you think it acomplishes what you were talking about.

Hi Kiger,

Had a look at the code and it looks great, the grouping of the validators will be very handy definately be testing it out tomorrow.

Most projects i work on follow Pear Coding Standards, so if i can i will make any additional code follow the existing code standards (in the case above, making sure the naming convention of methods are camelCase). As for coding standards, its all about maintainability. A coding standards document tells developers how they must write their code, instead of each developer coding in their own preferred style, they will write all code to the standards outlined in the document. This makes sure that a large project is coded in a consistent style.

Profile
 
 
Posted: 05 May 2007 09:44 PM   [ Ignore ]   [ # 5 ]  
Grad Student
Rank
Total Posts:  40
Joined  03-29-2006

I posted an updated today which fixed a MAJOR ISSUE with the code. In my run() function I incorrectly used an “OR” instead of an “AND” which caused all the validation to screw up. So if you were getting errors, or lack thereof, then you need this update. You can fix it yourself if you want.

Change line 152 from:

if ( !in_array('required', $ex, TRUE) OR !in_array('isset', $ex, TRUE) )

To:

if ( !in_array('required', $ex, TRUE) AND !in_array('isset', $ex, TRUE) )
Profile
 
 
Posted: 14 June 2007 04:11 PM   [ Ignore ]   [ # 6 ]  
Summer Student
Total Posts:  11
Joined  06-06-2007

Thanks kiger! This was one part of a solution for me. I mashed your validator solution:
http://codeigniter.com/forums/viewthread/51314/
with Shadi’s _POST multi-dimensional array solution:
http://codeigniter.com/forums/viewthread/51260/

Also of note is coolfactor’s extension:
http://codeigniter.com/forums/viewthread/53504/
and a core Validation fix:
http://codeigniter.com/forums/viewthread/48389/

Validation in models:
http://codeigniter.com/forums/viewthread/51767/

I’m new to CI and loving it; my biggest “disappointment” with CI so far is having to take time scrounging up this kind of critical info from various posts! I’m so used to looking up functions on php.net and scrolling down for extended info. I would love to just scroll down the Validation documentation to find these kinds of posts or links to related info :)

Profile
 
 
Posted: 09 August 2007 04:14 AM   [ Ignore ]   [ # 7 ]  
Summer Student
Total Posts:  4
Joined  08-09-2007
kiger - 28 April 2007 03:20 AM

FILE LINK TO MY_VALIDATION.PHP v1.22: http://www.filepanda.com/get/cusxoktx/

I couldn’t download the file in the given location long face

Profile
 
 
Posted: 09 August 2007 11:40 AM   [ Ignore ]   [ # 8 ]  
Moderator
Avatar
RankRankRankRank
Total Posts:  2139
Joined  07-30-2007

This definitely appears to be a great resource - I’ll be checking it out.

Thanks for the hard-work kiger!

 Signature 

Follow me on Twitter
MichaelWales.com

Profile
 
 
Posted: 25 August 2007 01:37 PM   [ Ignore ]   [ # 9 ]  
Grad Student
Rank
Total Posts:  68
Joined  05-19-2007

Before implementing this class I would get my error messages all at once. When using:

$this->validation->error_string
I would get something like:
The First name field is required
The Last Name field is required
The Address field is required

Now I get them one at a time. Is there a way to change this so I get them all at once again?

Profile
 
 
Posted: 24 September 2007 06:57 AM   [ Ignore ]   [ # 10 ]  
Summer Student
Total Posts:  7
Joined  09-11-2007

Does anyone know where this extension can be downloaded?  The above link does not work.

 Signature 

http://www.my-poker-odds.com

Profile
 
 
   
1 of 2
1
 
Post Marker Legend
New Topic New posts Hot Topic Hot Topic with new posts New Poll New Poll Moved Topic Moved Topic Sticky Topic Sticky topic
Old Topic No new posts Hot Old Topic Hot Topic with no new posts Old Poll Old Poll Closed Topic Closed Topic Announcement Announcements
Theme
Change Theme
Visitor Statistics
The most visitors ever was 719, on June 06, 2008 10:16 AM
Total Registered Members: 77521 Total Logged-in Users: 26
Total Topics: 101532 Total Anonymous Users: 2
Total Replies: 544296 Total Guests: 220
Total Posts: 645828    
Members ( View Memberlist )