CodeIgniter Form Validation - Get the Result as “a

2019-06-15 00:30发布

问题:

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.

回答1:

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.



回答2:

You can simply use,

$this->form_validation->error_array();

This is from the class reference documentation of CodeIgniter.



回答3:

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.



回答4:

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.



回答5:

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



回答6:

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>