I am using codeigniter 3.I have a email field in form and using required|callback_is_email_exist rules
on email.When I leave email field blank,it shows callback message instead of required message. I had worked on codeigniter 2 ,it perefctly shows "required" message, CI3 form validation not executing rules in the sequence when callbacks are used. Following is my code
View : welcome_message
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Welcome to CodeIgniter</title>
</head>
<body>
<?php echo validation_errors(); ?>
<?php echo form_open('Welcome'); ?>
<h5>Username</h5>
<input type="text" name="email" value="<?php echo set_value('email'); ?>" size="50" />
<div><input type="submit" value="Submit" /></div>
</form>
</body>
</html>
Controller:welcome.php
public function index()
{
$this->load->helper(array('form', 'url'));
$this->load->library('form_validation');
$this->form_validation->set_rules('email', 'Email', 'required|callback_is_email_exist');
if ($this->form_validation->run() == FALSE)
{
$this->load->view('welcome_message');
}
else
{
echo 'success';
}
}
public function is_email_exist($str)
{
// code to check email exist in databse here
if (is_email_exist($str)
{
return TRUE;
}
else
{
$this->form_validation->set_message('is_email_exist', 'Email Does not exist');
return FALSE;
}
}
Expected Output
email filed is required
Codeingiter 3 expects to execute rule in sequence.If one succeeds then next one executes.In this case if I leave email field blank it executes callback unnecessarily.Thus it shows wrong message.It should display email field is required instead of email does not exist.
Appreciate your feedback.
I do it so:
Create file: /application/libraries/MY_form_validation.php
<?php if (!defined('BASEPATH')) {
exit('No direct script access allowed');
}
class MY_Form_validation extends CI_Form_validation
{
public function __construct()
{
parent::__construct();
}
/**
* Your custom validation
*/
public function is_email_exist($str)
{
$CI =& get_instance();
// code to check email exist in databse here
if ($str=='test') {
return true;
}else {
$this->form_validation->set_message('is_email_exist', 'Email Does not exist');
return FALSE;
}
}
}
/* End of file MY_form_validation.php */
/* Location: ./application/libraries/MY_form_validation.php */
In controller (remove callback):
...
$this->form_validation->set_rules('email', 'Email', 'required|is_email_exist');
...
In controller remove function: callback_is_email_exist
.
But If you want to check if the email is unique to do so:
In controller:
...
$this->form_validation->set_rules('email', 'Email', 'required|valid_email|is_unique[users.email]',['is_unique'=>'Email exist!']);
...