在 set_rules() 中调用自定义帮助器或库函数
我试图在 set_rules(...) 行中调用自定义库的方法。
我听说可以创建一个类(在应用程序/库中)扩展本机 Form_validation 类并在那里编写自定义方法。
所以我有 /application/libraries/MY_Form_validation.php 和以下代码;
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));
}
}
}
在控制器的功能中我有;
...
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"; }
}
...
在 set_rules() 行中调用时,无法访问函数 ( test_my_method )。知道可能出了什么问题吗? 谢谢。
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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
我没有看到您没有使用回调函数而是扩展表单验证类来完成您的任务的任何原因。有关详细信息,请参阅回调:您自己的验证函数。如果您需要以某种方式改变其本机行为,则扩展该类,而不是为了此类任务。另外,如果您已经设置了一些自定义回调,则不需要包含其他规则(如修剪、必需等),因为您可以在自定义回调函数中检查该字段的所有方面。
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.