Codeigniter form_validation回调函数问题

my code is as follow:

class Test_model extends MY_Model
{
  public $validation_rules = [
    'field' => 'input_text',
    'label' => 'Your Text',
    'rules' => 'trim|callback_checkString',
    'errors' => [
      'checkString' => 'Invalid String',
    ]
  ];

  public function checkString($x){
    return $x==='valid';
  }

  /* callback function */
  public function do_my_job(){
    /*form_validation is already loaded in autoload.php*/
    $this->form_validation->set_rules($this->validation_rules);
    if($this->form_validation->run()){
      /*do something*/
    }else show_404();
  }
}

when I call $this->Test_model->do_my_job() all other validation works but callback function not works.... it always throws my custom error 'Invalid String' !!!...

any solution?...

You need to define an error message for your custom rule. In your case adding the message to $validation_rules would be very easy.

public $validation_rules = [
  'field' => 'input_text',
  'label' => 'Your Text',
  'rules' => 'trim|callback_checkString',
  'errors' => ['checkString' => '{field} text is not valid'],
];

The other option is to use the set_message method right after set_rules.

$this->form_validation
     ->set_rules($this->validation_rules)
     ->set_message('checkString', '{field} text is not valid');

Setting Error Messages Documentation

This next bit doesn't answer your question, but please consider this variation on checkString.

public function checkString($x)
{
  return $x==='valid'; //this will evaluate to a boolean, if/else not required
}

Part 2

The problem of a valid input not being validated is because of where the callback function is defined. Form_validation expects the validation method to be in the controller. (Technically, it actually looks for the method in the CI "super object" and that object IS the controller.) Moving the callback definition to the controller should cure all.

Part 3

If you want to make a custom validator available to your whole website and to keep your code DRY the easiest way to do that is to extend CI_Form_validation. Easier to do than you might think.

Create the file application/libraries/MY_Form_validation.php Here's the code

defined('BASEPATH') OR exit('No direct script access allowed');

class MY_Form_validation extends CI_Form_validation
{
  public function __construct($rules = array())
  {
    parent :: __construct($rules);
  }

  //Add any custom validation methods.

  public function checkString($x)
  {
    return $x === 'valid'; 
  }
}

DONE!

You load form validation exactly the same as always and you use your new method the same way you use the rules included with CI. You do not use the callback_ prefix.

Here's how your new rule would now be setup in your model.

public $validation_rules = [
  'field' => 'input_text',
  'label' => 'Your Text',
  'rules' => 'trim|checkString',
  'errors' => [
    'checkString' => 'Invalid String',
  ]
];

The do_my_job() method is unchanged.