CodeIgniter form validation, cannot get validation error

I am trying to use the CodeIgniters form validation library, and while my validation rules work, whenever I call validation_errors (), I get an empty string.

Here is a snippet of code.

$base_rules = 'required|trim'; $this->_validation_rules = array( array( 'field' => 'name', 'label' => 'name', 'rules' => $base_rules . '|alpha_numeric|min_length[5]|max_length[30]' ), array( 'field' => 'price', 'label' => 'Price', 'rules' => $base_rules . '|decimal' ), array( 'field' => 'duration', 'label' => 'Duration', 'rules' => $base_rules . '|integer' ), array( 'field' => 'booking', 'label' => 'Booking', 'rules' => $base_rules . '|integer' ) ); $this->form_validation->set_rules($this->_validation_rules); if ($this->form_validation->run()) { // do stuff }else{ // prints an empty string var_dump(validation_errors()); exit; } 

Does anyone know why this is so, and how can I get my mistakes?

+4
source share
3 answers

Put validation_errors () on top of your form and change your code to

  if ($this->form_validation->run()) { // do stuff }else{ $this->load->view('myform'); //display your form again } 

validation_errors () will only be poplated in the view.

+5
source

put this code at the top of the form in the view file

 echo validation_errors('<div>', '</div>'); 

then change else to

 else{ $this->load->view('myform'); //display your form again } 
+1
source

To complete John's answer, if you made a message on the form, you can put under your inputs:

 <?php echo form_error('input-name'); ?> 

But if you are making an ajax request (this is not your business now, but in the future, if you need to) you can use validation_errors ().

Here is an example:

  //Important to turn that off if it on $this->output->enable_profiler(false); $this->output->set_status_header('500'); $this->output->set_content_type('application/json'); echo json_encode(array( 'error_msg' => validation_errors(), )); 

And then on the client side you can use a response like this:

 error:function(data) { $("your-error-input-selector").html('').append(data.responseJSON.msg); } 

Hope I helped, even if I was one year late.

PS Sorry for my broken english.

+1
source

All Articles