CI3/ Validation Rules to a Config File & Using a callback

回眸只為那壹抹淺笑 提交于 2020-01-07 02:57:10

问题


I am unable to figure out where to place my callback when using validation rules to a config file in CI3. Here is my 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;
    }
}

However, when I run the above, I get the following error:

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

Where do I place the callback "html_length_without_html()"?


回答1:


You can extend or create a method inside the controller. I do prefer to "extend" with a helper function. Assuming that you are using $_POST:

application/helpers/form_validation_helper.php or just extending with 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;
    }
}

}

Nothing wrong with $ci->form_validation->set_message('html_length_without_html', 'The field can not be the word');, but if you're using the lang class, you should save the following line into application/language/english/form_validation_lang.php to get successfull callback response:

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

Don't forget to load the helper before use it: $this->load->helper('form_validation_helper'); or autoload, instead.



来源:https://stackoverflow.com/questions/40835999/ci3-validation-rules-to-a-config-file-using-a-callback

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!