phpformscodeignitervalidation

Passing multiple callback in Code Igniter form validation rules


I want to pass multiple callbacks in codeigniter form validation rules.... but only one of the callbacks work

I am using this syntax in my contoller

$this->form_validation->set_rules(           
                array(
                    'field' => 'field_name',
                    'label' => 'Field Name',
                    'rules' => 'callback_fieldcallback_1|callback_fieldcallback_2[param]',
                    'errors' => array(
                        'fieldcallback_1' => 'Error message for rule 1.',
                        'fieldcallback_2' => 'Error message for rule 2.',
                        )
                    ),
                );

and the callback functions are....

function fieldcallback_1 (){
      if(condition == TRUE){
              return TRUE;
      } else {
              return FALSE;
      }

}

function fieldcallback_2 ($param){
      if(condition == TRUE){
              return TRUE;
      } else {
              return FALSE;
      }

}

Someone please help me out with this problem.... any other solutions regarding passing multiple callbacks in form validation rules are also appreciated...


Solution

  • All validation routines must have at least one argument which is the value of the field to be validated. So, a callback that has no extra arguments should be defined like this.

    function fieldcallback_1($str){
          return ($str === "someValue");
    }
    

    A callback that requires two arguments is defined like this

    function fieldcallback_2 ($str, $param){
        //are they the same value?
        if($str === $param){
            return TRUE;
         } else {
             $this->form_validation->set_message('fieldcallback_2', 'Error message for rule 2.');
             //Note: `set_message()` rule name (first argument) should not include the prefix "callback_"
             return FALSE;
    }