如何在codeigniter 2中创建自定义验证规则?在整个应用程序中,哪些是常用的?
我知道我们可以在控制器中创建回调函数,然后可以在验证规则中使用-
$this->form_validation->set_rules('user_dob', 'Date of Birth', 'required|callback_validDate|callback_validAge');
现在我们可以在控制器中创建验证函数-
public function validDate($date) {
$d = DateTime::createFromFormat('d-M-Y', $date);
if ($d && $d->format('d-M-Y') == $date)
return TRUE;
$this->form_validation->set_message('validDate', ' %s is not in correct date format');
return FALSE;
}
但是有一个限制。我只能在那个特定的控制器中使用这个方法。此功能不能用于其他控制器。我将不得不重新编写相同的代码。
为此,我尝试使用给定的验证函数创建辅助文件,但还是没有成功。
那么我如何使用验证函数多次,创建一次在一个共同的文件在codeigniter ?
我也面临同样的问题。所以我遇到了一个创建验证函数的解决方案,在控制器中很常见。
在目录/application/libraries/
中创建一个文件MY_Form_validation.php
,代码如下-
<?php
if (!defined('BASEPATH'))
exit('No direct script access allowed');
class MY_Form_validation extends CI_Form_validation {
protected $CI;
function __construct() {
parent::__construct();
$this->CI = & get_instance();
}
function validDate($date) {
$this->CI->form_validation->set_message('validDate', ' %s is not in correct date format');
$d = DateTime::createFromFormat('d-M-Y', $date);
if ($d && $d->format('d-M-Y') == $date)
return TRUE;
return FALSE;
}
}
现在在你的控制器中,你可以使用函数名作为新规则-
$this->form_validation->set_rules('user_dob', 'Date of Birth', 'required|validDate|validAge');
如果需要,你可以在控制器的构造函数中加载库作为-
$this->load->library('form_validation');
欲了解更多信息,请参阅链接-https://arjunphp.com/custom-validation-rules-codeigniter/