EllisLab text mark
Advanced Search
     
Custom error message by field name
Posted: 22 October 2007 04:49 PM   [ Ignore ]
Joined: 2006-12-24
5 posts

Hi all!

I’m quite new to CI. I’d like to know if there’s a better way to create a custom error message for a specific field for a certain rule?

For example, I have 3 field test1, test2, test3. I want required rule error message for test1 to be woot, test2 to be wargh and test3 to be something else.


I did a few modifications the Validation library(copied it to the application/library folder and modified it there).

function set_custom_message($lang$field_name$val '')
{
  $this
->custom_error_message[$lang][$field_name] $val;

And modified the run function a little bit

// Did the rule test negatively?  If so, grab the error.
if ($result === FALSE)
{
    
if(array_key_exists($rule$this->custom_error_message))
    
{
        $custom_error 
$this->custom_error_message[$rule];
        if(
array_key_exists($field$custom_error))
        
{
            $line 
$custom_error[$field];
        
}
    }else{
        
if ( ! isset($this->_error_messages[$rule]))
        
{
            
if (FALSE === ($line $this->CI->lang->line($rule)))
            
{
                $line 
'Unable to access an error message corresponding to your field name.';
            
}
        }
        
else
        
{
            $line 
$this->_error_messages[$rule];;
        
}
    }

    
// Build the error message
    
$mfield = ( ! isset($this->_fields[$field])) ? $field $this->_fields[$field];
    
$mparam = ( ! isset($this->_fields[$param])) ? $param $this->_fields[$param];
    
$message sprintf($line$mfield$mparam);

    
// Set the error variable.  Example: $this->username_error
    
$error $field.'_error';
    
$this->$error $this->_error_prefix.$message.$this->_error_suffix;

    
// Add the error to the error array
    
$this->_error_array[] $message;
    continue 
2;