I’m new to working with Codeigniter and need to set a form validation rule and custom validation message for checking if the email address exists in the database that is submitted in a forgot password form. If the email address exists it sends an email, if it doesn’t it should reload the form, set the field value to what the user entered and provide an error that the email address doesn’t exist.
I’ve got the following in the controller…
public function forgot_password()
{
$this->form_validation->set_rules('email_address','Email Address','trim|required|valid_email');
if($this->form_validation->run() == FALSE)
{
$this->forgot_password_form();
}
else
{
$this->load->model('membership_model');
if($query = $this->membership_model->val_forgot_password())
{
$data['main_content'] = 'forgot_password_sent';
$this->load->view('includes/template', $data);
}
else
{
$this->form_validation->set_message('email_address','The email address you provided does not exist.');
$this->forgot_password_form();
}
}
}
and in the model…
public function val_forgot_password()
{
$this->db->where('email_address', $this->input->post('email_address'));
$query = $this->db->get($this->members);
if($query->num_rows == 1)
{
return true;
}
else
{
return false;
}
}
and the form is…
<?php
echo form_open('login/forgot_password');
echo "Email Address: " . form_input('email_address', set_value('email_address', ''));
echo br(2);
echo form_submit('submit','Send Email');
echo form_close();
echo br(1);
echo validation_errors('<p>Error: ');
?>
When the form is submitted with a valid email address it correctly goes to the success page but if the email address doesn’t exist, it appears to reload the form but does not give an error.
Help pls! 😀
You should use a callback to check the email exists. So your controller would be something like…
And your callback (still in your controller) would be something like…
All this is spelled out in the excellent CI docs here, and I would recommend sticking to the CI conventions if you are new to it.
http://codeigniter.com/user_guide/libraries/form_validation.html
EDIT: There is also another problem i was facing while doing this in codeigniter3. You have to named the message field name to the callback. So instead of
$this->form_validation->set_message('email_address', 'That email address don\'t exist, sucka!');This should be
$this->form_validation->set_message('_check_email_exists', 'That email address don\'t exist, sucka!');