1
votes

I used Codeigniter's built-in form validation library to validate a email input field.

This is my validation rule:

$this->form_validation->set_rules('email', '<b>email</b>', 'trim|htmlspecialchars|required|valid_email');

When using above validation rule everything is worked the way I espected.

For example:

  • If input field empty it shows: email is required.
  • If user input not a valid email, it shows: email is not valid.

Then I added custom form validation rule by adding callback function.

This is my modified validation rule:

$this->form_validation->set_rules('email', '<b>email</b>', 'trim|htmlspecialchars|required|valid_email|callback_mail_check');

And, This is my callback function:

public function mail_check() {

        if (!$this->users_model->get_user_by_email_address($this->input->post('email', TRUE))) {

            $this->form_validation->set_message('mail_check', 'Your <b>email</b> could not be found.');
            return FALSE;

        } else {
            return TRUE;
        }

    }

Now when I submit form without filling email field or submit with invalid email, its always out put custom callback function's validation message(Your email could not be found.).

But its not the way I wanted.

I want to first validate email field for empty values, then for valid email, after that callback_function.

1

1 Answers

4
votes

The validation rules you are using are correct. Just remove few rules those are not required

$this->form_validation->set_rules('email', '<b>email</b>', 'required|valid_email|callback_mail_check');

The callback automatically add the parameter of current validation. You don't need to read it from GET/POST method.

public function mail_check($email)
{
    if (!$this->users_model->get_user_by_email_address($email)) {

        $this->form_validation->set_message(__FUNCTION__, 'Your <b>email</b> could not be found.');
        return false;
    }
    return true;
}