I am getting an error when trying to set custom validation messages in CodeIgniter for the min_length and max_length validation constraints.
These are my validation rules:
$this->form_validation->set_rules('username', 'Username', 'required|xss_clean|min_length[6]|max_length[10]');
$this->form_validation->set_rules('password', 'Password', 'required|min_length[8]|max_length[20]';
These are my custom validation message:
$this->form_validation->set_message('min_length[3]', '%s: the minimum of characters is three');
$this->form_validation->set_message('max_length[20]', '%s:the maximum of characters is 20');
In my example we have two fields, but I have many fields with different minimum and maximum length values. They all have a specific constraint validations. This messages doesn't work. The message appears by default. Thanks for your help.
When using set_message, you can't specify the lengths (both min and max) the way that you have done. You can either set a general message for min_length and max_length like:
$this->form_validation->set_message('min_length', 'The value you have entered for %s is too short');
$this->form_validation->set_message('max_length', 'The value you have entered for %s is too long');
Otherwise, you will have to utilise CodeIgniter's callback feature and set up a custom validation function which would look something like this (for the minimum length!!).
public function custom_min_length($str, $val) {
if (preg_match("/[^0-9]/", $val)) {
return FALSE;
}
if (function_exists('mb_strlen')) {
if(mb_strlen($str) < $val) {
$this->form_validation->set_message('custom_min_length', '%s: The Minimum Number Of Characters Is ' . $val);
return FALSE;
} else {
return TRUE;
}
}
if(strlen($str) < $val) {
$this->form_validation->set_message('custom_min_length', '%s: The Minimum Number Of Characters Is ' . $val);
return FALSE;
} else {
return TRUE;
}
}
You would set your validation rule like this:
$this->form_validation->set_rules('username', 'Username', 'callback_custom_min_length[6]|required|xss_clean');
Notice the callback_ prefix on the custom_min_length rule. This replaces, and is used instead of the usual min_length CI function.
Hope that helps...I'll leave you figure out how to do the custom_max_length function :)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With