16

I am writing my form validation class using CodeIgniter. Is there any way so that I can get error messages in name value pair? For example, in a sample form there are four fields: user_name, password, password_conf, and timezone. Among them user_name and password validation has failed after executing the following:

$result = $this->form_validation->run();

If the above function returns false, I want to get the errors in name value pairs like the following:

Array
{
  'user_name' => 'user name is required',
  'password' => 'passord is required'
}

I truly want to form a JSON, which I can pass back to the AJAX call. I have a (dirty) solution: I can call validation methods one by one like the following:

$this->form_validation->required($user_name);
$this->form_validation->required($password);

Is there any other way, to get all the error messages at once in name value pair?

EDIT: I was suggested to do validation with jQuery from one of the answers:

jQuery will help in client side validation, but what about server side, there I am using CodeIgniter validation.

I have designed it so that:

  1. I post all the values using AJAX.
  2. Validate in server side (PHP).
  3. Perform the desired operation if the inputs are valid; else return error to the user.

7 Answers 7

16

I have found one way myself by looking into the CodeIgniter code: I have extended the library CI_Form_validation like: -

class MY_Form_validation extends CI_Form_validation
{
    public function getErrorsArray()
    {
        return $this->_error_array;
    }
}

I know, this is a hack, but will serve my need for the time. I hope CodeIginter team soon come up with an interface to access that array.

Sign up to request clarification or add additional context in comments.

6 Comments

It's not a hack at all, that's what OOP is all about. I am walking down the exact same road, and this is my end game since I see no other alternative.
This is definitively a good solution. Shame on codeigniter for not having this functionality natively!
This doesn't return a value though. Any idea why? When I dump the $this pointer, I see that _error_array is protected. The array always returns empty.
Works! Regarding last comment, my bad. I was dumping the array before the form_validation->run() and hence the empty array.
dont call oops a hack!!
|
5

You can simply use,

$this->form_validation->error_array();

This is from the class reference documentation of CodeIgniter.

Comments

1

The solution I like best doesn't involve adding a function anywhere or extending the validation library:

$validator =& _get_validation_object();
$error_messages = $validator->_error_array;

Reference: http://thesimplesynthesis.com/post/how-to-get-form-validation-errors-as-an-array-in-codeigniter/

You should be able to call this at any point in your code. Also, it's worth noting there is a newer thread that discusses this as well.

1 Comment

$this->form_validation->error_array(); is already in the library. Why not use it?
1

You can create an private function in your controller

    private function return_form_validation_error($input)
{
    $output = array();
    foreach ($input as $key => $value)
    {
        $output[$key] = form_error($key);
    }
    return $output;
}

and then in your validation method, just call this, here is mine

public function add_cat_form()
    {
        $this->output->unset_template();
        $this->load->library('form_validation');
        $this->form_validation->set_rules('name', 'Name', 'required');
        if ($this->form_validation->run())
        {
            if (IS_AJAX)
            {
                $dataForInsert = $this->input->post();
                if ($dataForInsert['parentid'] == -1)
                {
                    unset($dataForInsert['parentid']);
                }
                $this->post_model->add_cat($dataForInsert);
                echo json_encode('success');
            } else
            {
                #in case of not using AJAX, the AJAX const defined
            }
        } else
        {
            if (IS_AJAX)
            {
                #This will be return form_validation error in an array
                $output = $this->return_form_validation_error($this->input->post());
                echo $output = json_encode($output);
            } else
            {
                #in case of not using AJAX, the AJAX const defined
            }
        }
    }

Comments

0

Seeing as code igniter validation gives you the error messages on a normal page refresh wouldn't it be better to use something like the jquery validation plugin which will validate entirely client side before sending the form? No AJAX necessary that way.

EDIT: I'm not suggesting NOT DOING server side validation, just that posting with AJAX in order to validate isn't necessary and will reduce server hits if you do it client side. It will gracefully degrade to the regular page refresh with errors on or a success message.

3 Comments

Client side validation shouldn't be your only concern, backend validation is much more important.
Right that would be stupid. I did not suggest NOT DOING server side validation - read my edit AND original post again.
Also, sometimes validation NEED to be done backend, for example to validate something against a database table (unicity in a table)
0

there's already a correct answer but i think this one is more understandable on how to execute the process.

Do it in your Controller

$this->form_validation->set_rules('username', 'Username', 'required');
$this->form_validation->set_rules('password', 'Password', 'required');
if($this->form_validation->run() === FALSE){
    $data['error'] = validation_errors();
}else{
  //success
}
echo json_encode($data);

Do it in your JS

success:function(response){
 if(response.error){
  $('#notif').html(response.error); 
 }else{
   //do stuff here...
 }
}

and finally display the error corresponding to the given id in your js.

Do it in your HTML

<span id="notif"></span>

Comments

0

This might be way belated but I want to share a solution that I used in hope that it will benefit someone else.

Unfortunately, CodeIgniter's $this->form_validation->error_array() method returns only the errors that emanate from the set_rules() method. It does not account for the name of the form field that generated the error. However, we can leverage another of CodeIgniter's method $this->form_validation->error(), which returns the error(s) associated with a particular form field, by passing the name of the field as parameter.

//form validation rules
$this->form_validation->set_rules('f_name', 'First Name', 'trim|required', 
    ['required' => 'First Name is required']
);
$this->form_validation->set_rules('l_name', 'Last Name', 'trim|required', 
    ['required' => 'Last Name is required']
);
$this->form_validation->set_rules('email', 'Email', 'trim|required|valid_email|is_unique[users.email]', 
    [
        'required'      => 'Email is required',
        'valid_email'   => 'Email format is invalid',
        'is_unique'     => 'Email already exists'
    ]
);
$error_arr = []; //array to hold the errors
//array of form field names
$field_names= ['f_name', 'l_name', 'email'];
//Iterate through the form fields to build a field=error associative pair.
foreach ($field_names as $field) {
    $error = $this->form_validation->error($field);
    //field has error?
    if (strlen($error)) $error_arr[$field] = $error;
}

//print_r($error_arr);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.