Welcome Guest, Not a member yet? Register   Sign In
How to add your own custom errors to the form validation class
#1

[eluser]diez[/eluser]
Recently I've had the need to add custom form errors while using the form validation class. I know I can create a callback function within the set_rule() method. However, during certain situations this caused me to make duplicate database calls.

Here's how you would use the add_custom_error() function:

Controller
Code:
$this->load->library('form_validation');
    
if ($this->input->post('email') != $user_email_from_database)
{
    $this->form_validation->add_custom_error('email_field', "The email entered is not registered as an account.");  
}

if ($this->form_validation->run() == FALSE)
{    
     $this->load->view('login/login_view');
}

View
Code:
<html>

.......

<?php echo validation_errors(); ?> <!-- will display both native and custom errors-->

<h1>New User</h1>

&lt;?php echo form_open('login'); ?&gt;

<h5>Email Address</h5>
&lt;?php echo form_error('email'); ?&gt; &lt;!-- will display both native and custom errors--&gt;
&lt;input type="text" name="email" value="&lt;?php echo set_value('email'); ?&gt;" size="50" /&gt;

.......

<div>&lt;input type="submit" value="Submit" /&gt;&lt;/div>

&lt;/form&gt;

.......

&lt;/html&gt;


NOTE:

There are 2 ways of outputting the errors.

you can use:

Code:
1.) echo form_error('email'); &lt;!-- will display individual error msg associated with the form field  --&gt;

2.) echo validation_errors(); &lt;!-- will display all form error msgs as a batch --&gt;


native errors will be displayed first (if there are any) then, custom errors will be displayed in second priority.



If you want to use the add_custom_error() function extending the form validation class in CI, you can implement the following:

1.) Download the MY_Form_validation.php attachment and save it in your application/library folder


The only code added in the extended class is the following:

Code:
//***class variable we define at the top of our extended class

var $custom_field_errors = array(); //array that hold fields from errors



//***new function

function add_custom_error($field = '', $error_message = '')
{
    if($field == '')
    {
       return '';
    }
    $this->custom_field_errors[$field]  = $error_message;
    
    return true;
}



//***code snippet that is added into the run() method that we extend

//insert custom errors into native form validation error arrays
if(count($this->custom_field_errors) > 0)
{
    foreach($this->custom_field_errors as $field => $error_message)
    {
        $this->_error_array[$field] = $error_message;
        $this->_field_data[$field]['error'] = $error_message;
    }
}


Messages In This Thread
How to add your own custom errors to the form validation class - by El Forum - 01-26-2011, 05:29 PM



Theme © iAndrew 2016 - Forum software by © MyBB