CI3 /验证规则到配置文件&使用回调

时间:2016-11-28 01:37:53

标签: php codeigniter validation

在CI3中使用验证规则到配置文件时,我无法确定将回调放在何处。这是我的form_validation.php:

 <?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');

 $config = array(
   'blog_post' => array(

      array(
        'field' => 'entry_name', 
        'label' => 'entry_name', 
        'rules' => 'min_length[8]|trim|required|max_length[255]'
        ),

      array(
        'field' => 'entry_body', 
        'label' => 'entry_body', 
        'rules' => 'trim|required|min_length[12]|callback_html_length_without_html'
        ),
    ),
);

function html_length_without_html(){
   if (2 < 1)
    {
        $this->form_validation->set_message('html_length_without_html', 'The field can not be the word');
        return FALSE;
    } else {
        return TRUE;
    }
}

然而,当我运行上述操作时,我收到以下错误:

 Unable to access an error message corresponding 
 to your field name entry_body.(html_length_without_html)

我在哪里放置回调&#34; html_length_without_html()&#34;?

1 个答案:

答案 0 :(得分:1)

您可以extend或在控制器内创建方法。我更喜欢用辅助函数“扩展”。假设您使用$_POST

application / helpers / form_validation_helper.php 或只是使用MY_form_helper.php进行扩展:

<?php

if ( ! defined('BASEPATH')) exit('No direct script access allowed');

if (!function_exists('html_length_without_html')) {

function html_length_without_html() {
    $ci = & get_instance();
    $entry_body = $ci->input->post('entry_body');
    /*Do some check here to define if is TRUE or FALSE*/
    if ($entry_body < 1) {
        $ci->form_validation->set_message('html_length_without_html', 'The field can not be the word');
        return FALSE;
    }
    else {
        return TRUE;
    }
}

}

$ci->form_validation->set_message('html_length_without_html', 'The field can not be the word');没有错,但是如果您使用的是lang类,则应将以下行保存到application/language/english/form_validation_lang.php以获得成功的回调响应:

$lang['html_length_without_html'] = 'The field can not be the word';

在使用之前不要忘记加载帮助:$this->load->helper('form_validation_helper');autoload

相关问题