[eluser]Ollie Rattue[/eluser]
Hey, I am trying to replace the default validation rule error messages. I have changed some in languages/english/validation_lang.php but I need more specific things for certain forms so I am using if statements. I use a piece of code like this:
Code: if( $this->validation->run() == FALSE ): // validation hasn't been passed
if ($this->validation->headline_error != "") {
$this->validation->headline_error = "Please enter a snappy headline.";
}
Which works fine but I run into an issue if I have more than 2 rules on a field. The rules are setup like this in validation_lang.php.
$lang['required'] = "The %s field is required.";
$lang['matches'] = "Ooops! The passwords you entered do not match.";
So what I thought I could do is instead of running the if statement to catch all rules I would just catch the required error e.g.
Code: if ($this->validation->password_error == "The password field is required.") {
$this->validation->password_error = "You forgot to enter a password.";
}
For clarity the setup of this looks like:
$rules['password'] = "trim|required|xss_clean|matches[passwordconfirm]";
$fields['password'] = "password";
The text "The password field is required." is exactly what is printed out using <?=$this->validation->password_error;?> when i submit the form when and the password field is blank and I don't run any if statements. So I can't work out why my if statement doesn't pass as true.
I thought that maybe it is due to the %s not being set yet. But I have run this within the view file (not good form) and it still doesn't pass as true.
It has really got me stratching my head. Any ideas why this woudn't work?
[eluser]plainas[/eluser]
that was a bit confusing.
Anyway... Create your own validation function instead. With a few ifs set the error message acordingly and return false right after, then run your validation using a callback.
Just like it is in the user guide.
[eluser]ontguy[/eluser]
I think the Validation class has a function to do what you have in mind.
This would let you customize the error message for the rules you'd want changed:
Code: $this->validation->set_message('postcode', 'Error Message');
[eluser]Ollie Rattue[/eluser]
[quote author="ontguy" date="1218695518"]I think the Validation class has a function to do what you have in mind.
This would let you customize the error message for the rules you'd want changed:
Code: $this->validation->set_message('postcode', 'Error Message');
[/quote]
Hey ontguy. With this bit of code I can only have one error message, not different error messages depending on the rule which has not been met.
i need something like
Code: $this->validation->set_message('password','required', 'Please enter a password')
$this->validation->set_message('password','match', 'Your passwords do not match')
Sadly it looks like this might not exist, and it doesn't seem worth the time to start modifying the validation class.
P.S Sorry for the typo where I had postcode instead of password, it confused things a little. I have edited my initial post but this would explain why ontguy has postcode in his code snippet.
[eluser]Andrew A.[/eluser]
Hey Earthlion,
I was actually having the same issue earlier today, and I resolved it with a setup similar to what you had, however instead in my controller i had:
Code: if (!$this->validation->run())
{
if (isset($this->validation->accept_terms_error))
{
$this->validation->accept_terms_error = '.....';
}
With the isset check, everything went fine. In your example, PHP was checking to see if $this->validation->field_error = TRUE, which is not the case.
[eluser]codex[/eluser]
[quote author="EarthLion" date="1218727824"][quote author="ontguy" date="1218695518"]I think the Validation class has a function to do what you have in mind.
This would let you customize the error message for the rules you'd want changed:
Code: $this->validation->set_message('postcode', 'Error Message');
[/quote]
Hey ontguy. With this bit of code I can only have one error message, not different error messages depending on the rule which has not been met.
i need something like
Code: $this->validation->set_message('password','required', 'Please enter a password')
$this->validation->set_message('password','match', 'Your passwords do not match')
Sadly it looks like this might not exist, and it doesn't seem worth the time to start modifying the validation class.
P.S Sorry for the typo where I had postcode instead of password, it confused things a little. I have edited my initial post but this would explain why ontguy has postcode in his code snippet.[/quote]
I think I have done exactly what you need. If you want I can post it for you.
Basically what I did was extend the Validation class (MY_Validation) to allow me to do stuff like:
Code: $lang['default']['required'] = "This is a required field!";
$lang['user_name']['required'] = "You have to set a username";
$lang['emailaddress']['required'] = "Dude, what about an e-mailaddress?";
The first bracket corresponds with the fieldname. If no custom message is set, the default message is shown.
[eluser]codex[/eluser]
The class in parts:
Code: class MY_Validation extends CI_Validation{
var $CI;
var $error_string = '';
var $_error_array = array();
var $_rules = array();
var $_fields = array();
var $_error_messages = array();
var $_current_field = '';
var $_safe_form_data = FALSE;
var $_error_prefix = '<p>';
var $_error_suffix = '</p>';
var $language = array();
var $is_loaded = array();
/**
* Constructor
*
*/
function MY_Validation()
{
parent::CI_Validation();
$this->CI =& get_instance();
log_message('debug', "MY_Validation Class Initialized");
}
// --------------------------------------------------------------------
function set_message($callback = '', $fieldname = '', $message= '')
{
$data[$fieldname] = array($callback => $message);
$this->_error_messages = array_merge($this->_error_messages, $data);
}
// --------------------------------------------------------------------
/**
* Load a language file
*
* @access public
* @param mixed the name of the language file to be loaded. Can be an array
* @param string the language (english, etc.)
* @return void
*/
function load($langfile = '', $idiom = '', $return = FALSE)
{
$langfile = str_replace(EXT, '', str_replace('_lang.', '', $langfile)).'_lang'.EXT;
if (in_array($langfile, $this->is_loaded, TRUE))
{
return;
}
if ($idiom == '')
{
$deft_lang = $this->CI->config->item('language');
$idiom = ($deft_lang == '') ? 'english' : $deft_lang;
}
// Determine where the language file is and load it
if (file_exists(APPPATH.'language/'.$idiom.'/'.$langfile))
{
include(APPPATH.'language/'.$idiom.'/'.$langfile);
}
else
{
if (file_exists(BASEPATH.'language/'.$idiom.'/'.$langfile))
{
include(BASEPATH.'language/'.$idiom.'/'.$langfile);
}
else
{
show_error('Unable to load the requested language file: language/'.$langfile);
}
}
if ( ! isset($lang))
{
log_message('error', 'Language file contains no data: language/'.$idiom.'/'.$langfile);
return;
}
if ($return == TRUE)
{
return $lang;
}
$this->is_loaded[] = $langfile;
$this->language = array_merge($this->language, $lang);
unset($lang);
log_message('debug', 'Language file loaded: language/'.$idiom.'/'.$langfile);
return TRUE;
}
[eluser]codex[/eluser]
Second part:
Code: /**
* Fetch a single line of text from the language array
*
* @access public
* @param string the language line
* @return string
*/
function line($line = 'default', $rule = 'required')
{
return ($line == '' OR ! isset($this->language[$line][$rule])) ? FALSE : $this->language[$line][$rule];
}
[eluser]codex[/eluser]
Last part:
Code: function run()
{
// Do we even have any data to process? Mm?
if (count($_POST) == 0 OR count($this->_rules) == 0)
{
return FALSE;
}
// Load the language file containing error messages
$this->load('validation');
// Cycle through the rules and test for errors
foreach ($this->_rules as $field => $rules)
{
//Explode out the rules!
$ex = explode('|', $rules);
// Is the field required? If not, if the field is blank we'll move on to the next test
if ( ! in_array('required', $ex, TRUE))
{
if ( ! isset($_POST[$field]) OR $_POST[$field] == '')
{
continue;
}
}
if ( ! isset($_POST[$field]))
{
if (in_array('isset', $ex, TRUE) OR in_array('required', $ex))
{
if ( ! isset($this->_error_messages['isset']))
{
if (FALSE === ($line = $this->line($field, 'isset'))) // Use internal 'line' function
{
$line = 'The field was not set';
}
}
else
{
$line = $this->_error_messages['default']['isset']; // Add default
}
// Build the error message
$mfield = ( ! isset($this->_fields[$field])) ? $field : $this->_fields[$field];
$message = sprintf($line, $mfield);
// Set the error variable. Example: $this->username_error
$error = $field.'_error';
$this->$error = $this->_error_prefix.$message.$this->_error_suffix;
$this->_error_array[] = $message;
}
continue;
}
$this->_current_field = $field;
// Cycle through the rules!
foreach ($ex as $rule)
{
// Strip the parameter (if exists) from the rule
// Rules can contain a parameter: max_length[5]
$param = FALSE;
if (preg_match("/(.*?)\[(.*?)\]/", $rule, $match))
{
$rule = $match[1];
$param = $match[2];
}
if ( ! method_exists($this, $rule))
{
if (function_exists($rule))
{
$_POST[$field] = $rule($_POST[$field]);
$this->$field = $_POST[$field];
}
continue;
}
$result = $this->$rule($_POST[$field], $param);
// Did the rule test negatively? If so, grab the error.
if ($result === FALSE)
{
if ( ! isset($this->_error_messages[$field][$rule]))
{
if (FALSE === ($line = $this->line($field, $rule)))
{
$line = $this->line('default', $rule);
}
}
else
{
$line = $this->_error_messages[$field][$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;
}
}
}
$total_errors = count($this->_error_array);
if ($total_errors > 0)
{
$this->_safe_form_data = TRUE;
}
$this->set_fields();
// Did we end up with any errors?
if ($total_errors == 0)
{
return TRUE;
}
// Generate the error string
foreach ($this->_error_array as $val)
{
$this->error_string .= $this->_error_prefix.$val.$this->_error_suffix."\n";
}
return FALSE;
}
[eluser]Khoa[/eluser]
Hi codex, this is exactly what I'm looking for. But can you just upload the lib as a whole so that people can download, and can you also give an example of how it can be used? :-P Sorry that I'm a bit lazy, just want the quickest way to make the thing work. Thanks.
|