Welcome Guest, Not a member yet? Register   Sign In
Custom validation depends exclusively on callbacks: doesn't work without "required"
#1

[eluser]CodeIgniterNewbie[/eluser]
My application allows users to create their own forms and assign custom field validations to each form field. Currently, the validation users can select are regex-based (e.g. required, minimum characters, maximum charactes, matches a certain pattern, etc.). It supports ANDing and ORing of each rule, etc. Everything is stored nicely in the database and works perfectly.

I cannot use any of CodeIgniter's validation rules as there is no way to predict what kind of validations a user may require. I have to depend entirely on my custom validation via callbacks.

So, to set a rule, I loop through database records and assign rules somewhat like this:

Code:
foreach ($rules as $rule)
    {
       $field_id = $rule['field_id'];
       $this->form_validation->set_rules($rule['field_name'], $rule['field_label'], "callback__foobar[$field_id]");
    }

My callback looks like this:
Code:
public function _foobar($post, $field_id)
    {
       // Loop through all the validation rules defined in the database for the $field_id
    
       // Failed validation:
       $this->form_validation->set_message('_foobar', 'Validation failed.');
       return FALSE;
    
       // Passed validation:
       return TRUE;
    }
My custom validation works fine -- **as long as some value is entered in the field**. If the field is empty, nothing is passed to my callback's $post and $field_id parameters. I expect $post to be empty, however $field_id being empty also is causing problems. I need to know what $field_id is so I can run my custom validation rules on the appropriate field.

How do I solve this?

EDIT:

My guess is that my problem lays in Form_validation.php line 482:

Code:
// If the field is blank, but NOT required, no further tests are necessary
$callback = FALSE;
if ( ! in_array('required', $rules) AND is_null($postdata))
{
   // Before we bail out, does the rule contain a callback?
   if (preg_match("/(callback_\w+)/", implode(' ', $rules), $match))
   {
      $callback = TRUE;
      $rules = (array('1' => $match[1]));
   }
   else
   {
      return;
   }
}
#2

[eluser]WanWizard[/eluser]
Correct.

If you don't define the field as required, it's ok if it is empty. And if it's empty, why would you run any rules, as there is nothing to validate?
#3

[eluser]CodeIgniterNewbie[/eluser]
Because I want my validation routines to exclusively take over (including checking if "required" is met). Any idea how I can do this?
#4

[eluser]WanWizard[/eluser]
Extend the form validation class, copy the _execute() method over, and modify it to your liking.




Theme © iAndrew 2016 - Forum software by © MyBB