CaTz
CaTz

Reputation: 315

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[].

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?

Upvotes: 2

Views: 20963

Answers (2)

Jacky Supit
Jacky Supit

Reputation: 567

This is my custom Form_Validation class. 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;
    }
}

Upvotes: 3

janosrusiczki
janosrusiczki

Reputation: 1931

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.

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.

Hope this helps.

Upvotes: 2

Related Questions