1

我制作了一个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 中给出的示例构建了我自己的库,特别是关于“扩展form_validation”的库。我错过了一个步骤或一些特殊的部分吗?

4

2 回答 2

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');
于 2013-01-27T16:11:09.013 回答
0

您无需创建单独的函数即可在 CodeIgniter 中运行正则表达式验证。它允许您像这样指定正则表达式:

$this->form_validation->set_rules('FieldName', 'field name', 'regex_match[#[a-zA-Z]#]');
于 2013-01-31T22:34:01.727 回答