CI3 /验证规则到配置文件&使用回调 [英] CI3/ Validation Rules to a Config File & Using a callback
问题描述
我无法找出在CI3中使用验证规则到配置文件时在何处放置回调。这是我的form_validation.php:
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)
我在哪里放置回调html_length_without_html()?
Where do I place the callback "html_length_without_html()"?
推荐答案
您可以 extend 或在控制器内创建一个方法。我喜欢扩展一个帮助函数。假设您使用 $ _ POST
:
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 或者只是扩展与MY_form_helper.php:
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;
}
}
}
没有错与 $ ci-> form_validation-> set_message('html_length_without_html','字段不能是字');
,但如果你使用lang类,您应该将以下行保存到 application / language / english / form_validation_lang.php
以获得成功的回调响应:
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';
不要忘记在使用之前加载助手: $ this- > load-> helper('form_validation_helper');
或 autoload 。
Don't forget to load the helper before use it: $this->load->helper('form_validation_helper');
or autoload, instead.
这篇关于CI3 /验证规则到配置文件&使用回调的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!