[eluser]bretticus[/eluser]
[quote author="iNfLuX" date="1240363613"]
How can i set a global error message for a specific form ?...
but it's not my case cause I am trying to validate not only the username field.[/quote]
Perhaps, you are having the issue that I am just addressing. I have 3 drop-downs for a date (month, day, and year.) Callback could work for this I suppose, I could have just referenced the 3 input fields in the callback method but I wanted a way to just inject an arbitrary error into Form Validation so that $this->form_validation->run() catches it as well. I decided to extend the Form_validation class with a very simple new method:
Code:
<?php if (!defined('BASEPATH')) exit('No direct script access allowed');
/*** Brett: Thu Apr 23 16:48:00 GMT 2009
* Extension for adding arbitrary error messages ***/
class MY_Form_validation extends CI_Form_validation {
function MY_Form_validation($rules=array())
{
parent::CI_Form_validation($rules);
}
function create_arbitrary_error($alias, $message) {
// Save the error message
$this->_field_data[$alias]['error'] = $message;
if ( ! isset($this->_error_array[$alias]))
{
$this->_error_array[$alias] = $message;
}
}
}
?>
This seems to do the trick. That is, the $this->form_validation->run() fails if I call this method, and the form_error() function works for showing the error right where I want to on my form.
For example, I call this BEFORE calling $this->form_validation->run() :
Code:
if ( checkdate(
$this->input->post('birthdate_month', TRUE),
$this->input->post('birthdate_day', TRUE),
$this->input->post('birthdate_year', TRUE)
) === FALSE )
{
$this->form_validation->create_arbitrary_error('birthdate', 'Date of Birth is invalid');
}
In my view, I simply have...
Code:
<p>
<label><strong>Birthdate:</strong> <?php echo form_dropdown('birthdate_month', getmonths(), set_value('birthdate_month')); ?> </label>
<label> <?php echo form_dropdown('birthdate_day', array_merge(array('Day'), range(1, 31)), set_value('birthdate_day')); ?> </label>
<label> <?php echo form_dropdown('birthdate_year', array_merge(array('Year'), array_combine(range(1900, date('Y')), range(1900, date('Y')))), set_value('birthdate_year')); ?> </label>
<?php echo form_error('birthdate'); ?></p>
I am somewhat new to CI. However, this is working for me, but I would love to hear suggestions on how others have handled similar scenarios (excluding the suggestion that I should have just one date field instead of three drop-downs. I actually may go that route, but there are still other circumstances where something like I have done may be necessary. Surely, form validation rules can't address every scenario where you validate multiple related fields?)