[eluser]CroNiX[/eluser]
Well, that's not how the validation class was designed to be used. The only way to set custom error messages is to either override the global messages, or to create your own validation rules by either extending the form validation library or using validation callbacks (which can only be in a controller using stock CI).
The only way to set error messages is by the validation rule name, which is why the above will work.
for instance, you could create:
/application/libraries/MY_Form_validation.php
Code:
class MY_Form_validation extends CI_Form_validation {
function __construct($config = array())
{
parent::__construct($config);
}
function username_match($str) //str is the value from the form field this rule was used on
{
if( ! preg_match('/(A-Za-z0-9)+/', $str))
{
//error message must be same as function name
$this->set_message('username_match', 'The %s field must only contain alpha-characters or numbers!');
return FALSE; //failed
}
return TRUE; //passed
}
}
then in your controller
Code:
$this->load->library('form_validation'); //load validation, it will autoload your MY_Form_validation
$this->form_validation->set_rules('your-username-field', 'Username', 'required|username_match); //set the new rule to this field
If there is an error on 'your-username-field', it will output the error "The Username field must only contain alpha-characters or numbers!"