CodeIgniter Forums

Full Version: Form validation class should allow static or object-based rules
You're currently viewing a stripped down version of our content. View the full version with proper formatting.

El Forum

[eluser]Unknown[/eluser]
The Form Validation class does not allow users to specify static function callbacks or function callbacks referencing other objects. For example, a UserM model might exist with the static function IsValidUsername. Letting multiple controllers call this would be very convenient. Currently, that function would need to be tied to the current controller. For example, the following snippet should work:

Code:
$this->form_validation->set_rules('username', 'Username', 'required|UserM::IsFreeUsername');

This can be fixed (in a backwards compatible way) by changing (in SVN rev. 1595):

Form_validation.php:622 from:
Code:
if (function_exists($rule))
to:
Code:
if (is_callable($rule))

and Form_validation.php:622 from:
Code:
$result = $rule($postdata);
to:
Code:
$result = call_user_func($rule, $postdata);


This can also be made to support validation langs by changing (in Form_validation.php:636):
Code:
continue;
                }

                $result = $this->$rule($postdata, $param);

                if ($_in_array == TRUE)
                {
                    $this->_field_data[$row['field']]['postdata'][$cycles] = (is_bool($result)) ? $postdata : $result;
                }
                else
                {
                    $this->_field_data[$row['field']]['postdata'] = (is_bool($result)) ? $postdata : $result;
                }


to

Code:
//continue;
                }else{

                    $result = $this->$rule($postdata, $param);

                    if ($_in_array == TRUE)
                    {
                        $this->_field_data[$row['field']]['postdata'][$cycles] = (is_bool($result)) ? $postdata : $result;
                    }
                    else
                    {
                        $this->_field_data[$row['field']]['postdata'] = (is_bool($result)) ? $postdata : $result;
                    }
                }

This change allows the following code to work in system/language/english/form_validation_lang.php:
Code:
$lang['UserM::IsFreeUsername'] = "That username is taken. Please choose another.";

El Forum

[eluser]Colin Williams[/eluser]
Looks good to me.

El Forum

[eluser]xwero[/eluser]
moving the rules outside the validation class is something that is on my feature wish list for a long time so any solution in this direction has my support.