我在custom_form_validation.php
中创建了一个application\libraries
文件,其中包含:
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class Custom_form_validation extends CI_Form_validation {
function Custom_form_validation()
{
parent::__construct();
}
/* at_least_one_letter() by Ben Swinburne
* http://stackoverflow.com/a/9218114/1685185
-----------------------------------------------*/
public function has_at_least_one_letter( $string )
{
$result = preg_match('#[a-zA-Z]#', $string);
if ( $result == FALSE ) $this->set_message('has_at_least_one_letter', 'The %s field must have at least one letter.');
return $result;
}
}
然后我将它加载到特定的控制器中:
$this->load->library('form_validation');
$this->load->library('custom_form_validation');
最后,我使用函数has_at_least_one_letter
作为:
$this->form_validation->set_rules('FieldName', 'field name', 'has_at_least_one_letter');
我不知道出了什么问题,因为我按照SO中给出的示例来构建我自己的库,特别是关于“extends form_validation
”的库。我错过了一个步骤或一些特殊的部分吗?
答案 0 :(得分:1)
自定义库扩展了CI_Form_Validation:
库\ 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 has_at_least_one_letter($string) {
$this->CI->form_validation->set_message('has_at_least_one_letter', 'The %s field must have at least one letter.');
return preg_match('#[a-zA-Z]#', $string);
}
然后使用
$this->form_validation->set_rules('FieldName', 'field name', 'has_at_least_one_letter');
答案 1 :(得分:0)
您无需在CodeIgniter中创建单独的函数来运行regex验证。它允许您像这样指定正则表达式:
$this->form_validation->set_rules('FieldName', 'field name', 'regex_match[#[a-zA-Z]#]');