hairynuggets hairynuggets - 1 year ago 94
PHP Question

Creating a custom codeigniter validation rule

I have a function in my login form that checks if the email and password match the values in the database and if so it logs the user into the system.

I would like to display a validation error if this function returns false.

My problem is that I am unsure how to go about creating this. The message relates to both the password and email fields so I would not want a rule for each input field just display a single message.

I have tried using flashdata to achieve this but it only works when the page has been refreshed.

How can I created a new validation rule solely for the function


$this->form_validation->set_error_delimiters('<div class="error">', '</div>');
$this->form_validation->set_rules('email_address', '"Email address"', 'trim|required|valid_email');
$this->form_validation->set_rules('password', '"Password"', 'trim|required');

if ($this->form_validation->run() == FALSE)
$viewdata['main_content'] = 'members/login';
$this->load->view('includes/template', $viewdata);

Answer Source

You use the callback_ in your rules, see callbacks, for ex.

$this->form_validation->set_rules('email_address', '"Email address"', 'trim|required|valid_email|callback_validate_member');

and add the method in the controller. This method needs to return either TRUE or FALSE

function validate_member($str)
   $field_value = $str; //this is redundant, but it's to show you how
   //the content of the fields gets automatically passed to the method

     return TRUE;
     return FALSE;

You then need to create a corresponding error in case the validation fails

$this->form_validation->set_message('validate_member','Member is not valid!');
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download