i’m trying to setup a codeigniter form with different error messages.
set_message(rule, msg) is setting up a message for the whole form.
I need:
$this->form_validation->set_rules('name', 'First Name', 'required');
$this->form_validation->set_message('name', 'required', 'Enter your Name');
$this->form_validation->set_rules('second', 'Variables', 'required');
$this->form_validation->set_message('second', 'required',
'The Variables are required');
Adding the %s into the message string is no help in this case, since the messages have to be completely different.
Possibly I could do something like:
controller
$this->form_validation->set_rules('name', 'Name',
'required|min_length[6]|max_length[12]');
$this->form_validation->set_rules('second', 'Variables',
'required|min_length[3]|max_length[5]');
$this->form_validation->set_message('required', 'required');
$this->form_validation->set_message('min_length', 'short');
$this->form_validation->set_message('max_length', 'long');
view
switch(form_error('name')) {
case '<p>required</p>':
echo 'Enter your Name';
break;
case '<p>short</p>':
echo 'min length 6';
break;
case '<p>long</p>':
echo 'min length 12';
break;
}
switch(form_error('second')) {
case '<p>required</p>':
echo 'The Variables are required';
break;
case '<p>short</p>':
echo 'min length 3';
break;
case '<p>long</p>':
echo 'min length 5';
break;
}
But isn’t there a smarter way to do it?
I think a smarter way would be to use Codeigniter’s callback feature (something similar to below). The following works but it may be possible to streamline it even more. If nothing else, it’s a starting point.
Create two callback functions (I’ve named these custom_required and custom_check_length) and place them at the bottom of your controller (or wherever you feel necessary).
and…
These two functions take care of the set_message aspect of your form validation. To set the rules, you simply need to call these two functions by prefixing the function name with callback_.
So…
I hope the above helps in some way!!