How to show validation message in controller Codeigniter

How can I use {ci_form_validation field='title' error='true'} in the controller ?

I have this code

$this->load->library('form_validation');
$this->form_validation->set_rules('title', $this->lang->line('title'), 'trim|required|min_length[3]|xss_clean');   
$this->form_validation->set_rules('fahad', $this->lang->line('blog'), 'trim|required|min_length[20]|xss_clean'); 
$this->form_validation->set_rules('writer', $this->lang->line('writer'), 'trim|required|alpha_dash|min_length[3]|xss_clean');

I want to print error message in controller because I am using jquery.

Upvotes: 3

Views: 7871

Answers (2)

Muhammad Raheel
Muhammad Raheel

Reputation: 19882

Use this from user guide

echo form_error('field_name');

EDITED

ok try

echo validation_errors();

this will give you every error after that you can get what you want

Upvotes: 6

cmpreshn
cmpreshn

Reputation: 162

Actually, there is no way to do this with CodeIgniter out of the box. However, it is quite easy to extend the original form validation library.

  • create a file titled "MY_Form_validation.php" in your application/libraries folder

  • add the following code to application/libraries/MY_Form_validation.php

    class MY_Form_validation extends CI_Form_validation {
    
        public function __construct() {
    
            parent::__construct();
    
        }
    
        /**
         * Return all validation errors
         *
         * @access  public
         * @return  array
         */
        function get_all_errors() {
    
            $error_array = array();
    
            if (count($this->_error_array) > 0) {
    
                foreach ($this->_error_array as $k => $v) {
    
                    $error_array[$k] = $v;
    
                }
    
                return $error_array;
    
            }
    
            return false;
    
        }
    
    
    }
    

Then from your controller:

    echo "<pre>";

    print_r($this->form_validation->get_all_errors());

    echo "</pre>";

Upvotes: 1

Related Questions