简体   繁体   中英

CodeIgniter Form Validation - Get the Result as “array” Instead of “string”

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.

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.

You can simply use,

$this->form_validation->error_array();

This is from the class reference documentation of CodeIgniter.

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.

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 } } }

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.

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>

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);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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