0

With Codeigniter you can validate forms with the form_validation library. However I don't use this all the time but I like to use the form_error('fieldname') function.

Is it possible to push a error message to a field manually without doing form_validation->run().

2 Answers 2

6

I found a Codeigniter way to add the functionality I want. By extending the system/libraries/Form_validation.php.

First create file: application/libraries/MY_Form_validation.php

Then extend the CI_Form_validation class:

<?php
/**
 * Created by PhpStorm.
 * User: william
 * Date: 02/02/2016
 * Time: 22:56
 */

class MY_Form_validation extends CI_Form_validation{

    /**
     * set error message
     *
     * sets the error message associated with a particular field
     *
     * @param   string  $field  Field name
     * @param   string  $error      Error message
     */
    public function setError($field, $error){
        $this->_field_data[$field]['error'] = $error;
    }

}

Now you can use the form_validation->setError('fieldname','error') to manualy set error messages:

class Test extends CI_Controller{

    function index(){

        $this->load->library('form_validation');

        if (/* your validation outside of the form_validation */) {
            $this->form_validation->setError('username', 'Invalid login credentials');      
        }

        $this->load->view('test');
    }

}

Note! Use this when you want to do some custom validation without using a callback

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

Comments

2

No, that function is only designed to work with the Form_validation library.

2 Comments

can i add image validation error in validation_errors of codeigniter?
sir, can it possible to get only error in validation_errors();

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.