简体   繁体   English

如何使用form_validation和CodeIgniter设置自定义错误消息

[英]How to set custom error message with form_validation And CodeIgniter

i am newbie in CodeIgniter...and i am trying to do form validation for array input... the array name is pages[]. 我是CodeIgniter的新手...并且我正在尝试对数组输入进行表单验证...数组名称为pages []。

and i wrote: 我写道:

$this->form_validation->set_rules('pages[]','','required');

if i use that: 如果我用那个:

$this->form_validation->set_message('required', 'you not selected pages.');

it will not change the other "required" validation input params? 是否不会更改其他“必需”的验证输入参数?

So how can i set error message only for one validation? 那么,如何只为一个验证设置错误消息?

It doesn't work like you stated, you should read this section of the user guide more carefully. 它不能像您所说的那样工作,您应该更仔细地阅读用户指南的这一部分

I'm not sure I can explain better, but the first field of the set_message method doesn't refer to the type of validation but to the callback function's name, that's the function which is doing the custom validation work. 我不确定我能否解释得更好,但是set_message方法的第一个字段不是指验证的类型,而是指回调函数的名称,该函数正在执行自定义验证工作。

What you need to do is define your callback function (the guide has a good example), in which you iterate through your array's elements and count what's checked. 您需要做的是定义回调函数(该指南提供了一个很好的示例),您可以在其中循环访问数组的元素并计算检查的内容。 If at the end of the iteration the counter is 0 you set your error message. 如果在迭代结束时计数器为0,则设置错误消息。

Hope this helps. 希望这可以帮助。

This is my custom Form_Validation class. 这是我自定义的Form_Validation类。 you can use it if you want to. 您可以根据需要使用它。 put this file under your libraries directory. 将此文件放在您的库目录下。 then you can use the set message like this: 那么您可以使用以下设置消息:

$this->form_validation->setError(YOUR_INPUT_NAME, THE_MESSAGE);  

ex: $this->form_validation->setError('email', 'Invalid email');  

-- -

class MY_Form_validation extends CI_Form_validation {
    public function set_error($field, $pesan_error){
        $this->_field_data[$field]['error'] = $pesan_error;
    }
    public function get_error($field){
        return $this->_field_data[$field]["error"];
    }
    public function get_all_error(){
//        return $this->_field_data[$field]["error"];

        $fields = $this->_field_data;
        $pesan = "";
        foreach($fields as $field ) {
            if($field["error"]) {
                $pesan .= "<p>$field[error]</p>";
            }
        }
        return $pesan;
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM