Reputation: 714
I am using code igniter form_validation class to perform a number of validations, since codeigniter validates all the fields and then shows a list of all the errors, I need to restrict this to show only the first error that occurred.
Eg.
If I have 2 (email, message) fields with the required
validation in place, and if I were to leave both fields blank. I need codeigniter to show only the error The Email Field is required.
Upvotes: 0
Views: 471
Reputation: 35190
To my knowledge CI doesn't come with this out of the box, but it's easy enough to implement:
Firstly, (if you don't have this file already) create the file MY_Form_validation.php
in application/libraries/ with the following:
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class MY_Form_validation extends CI_Form_validation {
public function __construct($rules = array())
{
parent::__construct($rules);
}
}
Then add the following method to that class:
/**
* First Error
*
* Returns the first error messages as a string, wrapped in the error delimiters
*
* @access public
* @param string
* @param string
* @return str
*/
public function first_error($prefix = '', $suffix = '')
{
// No errrors, validation passes!
if (count($this->_error_array) === 0)
{
return '';
}
if ($prefix == '')
{
$prefix = $this->_error_prefix;
}
if ($suffix == '')
{
$suffix = $this->_error_suffix;
}
// Generate the error string
$str = '';
foreach ($this->_error_array as $val)
{
if ($val != '')
{
return $prefix.$val.$suffix."\n";
}
}
return $str;
}
This way you'll be able to access this with $this->form_validation->first_error()
Alternatively, you can create a helper function similar to validation_errors()
by (if the file doesn't exist) creating a file called MY_form_helper.php
in application/helpers/
and then adding the following code:
/**
* First Validation Error String
*
* Returns the first error associated with a form submission. This is a helper
* function for the form validation class.
*
* @access public
* @param string
* @param string
* @return string
*/
if ( ! function_exists('first_validation_error'))
{
function first_validation_error($prefix = '', $suffix = '')
{
if (FALSE === ($OBJ =& _get_validation_object()))
{
return '';
}
return $OBJ->first_error($prefix, $suffix);
}
}
Hope this helps!
Upvotes: 4