CodeIgniter Forums
Custom error message by field name - Printable Version

+- CodeIgniter Forums (https://forum.codeigniter.com)
+-- Forum: Archived Discussions (https://forum.codeigniter.com/forum-20.html)
+--- Forum: Archived Libraries & Helpers (https://forum.codeigniter.com/forum-22.html)
+--- Thread: Custom error message by field name (/thread-3800.html)



Custom error message by field name - El Forum - 10-22-2007

[eluser]mkhairul[/eluser]
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).

Code:
function set_custom_message($lang, $field_name, $val = '')
{
  $this->custom_error_message[$lang][$field_name] = $val;
}

And modified the run function a little bit
Code:
// 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;
}