I am trying to call a custom library's method in the set_rules(...) line.
I heard one could create a class (in application/libraries) extending the native Form_validation class and write the custom methods there.
So I have /application/libraries/MY_Form_validation.php with the following code;
class MY_Form_validation extends CI_Form_validation {
public function __construct()
{
parent::__construct();
}
function test_my_method($str)
{
//echo "test"; exit;
if ( ! is_array($str))
{
return (trim($str) == '') ? FALSE : TRUE;
}
else
{
return ( ! empty($str));
}
}
}
and in a controller's function I have;
...
public function login() {
$this->load->library('form_validation');
//echo ($this->form_validation->test_my_method(''))? "true":"false";
$this->form_validation->set_rules('username', 'Username', 'trim|test_my_method');
$this->form_validation->set_rules('password', 'Password', 'required');
if($this->form_validation->run())
{ echo "Success"; }
}
...
The function ( test_my_method ) is开发者_高级运维 not accessible when called in the set_rules() line. Any idea what could be wrong?. Thanks.
I didn't see any reason why you didnt use callback function instead extending the form validation class, for your task. See Callbacks: Your own Validation Functions for details. You did, extends the class if you need to change somehow from its native behaviour, not for this kind of task. Also, in addition, if you already set some custom callback, you doesn't need to include the other rule (like trim, required and so on) since you can inspect all aspect of that field within your custom callback function.
精彩评论