当用户转到设置以更改他/她的电子邮件,用户名,名字等时,它会验证他尝试更改为的电子邮件是否已存在于数据库中,如果存在,则他无法保存更改。但是,默认情况下,is_unique
仅检查该值是否存在于数据库中,而不检查该值是否存在并且属于用户。例如,如果用户正在更改他的信息,并且他没有更改他的电子邮件,而是更改了他的姓名和内容,他无法更改它,因为它会说"电子邮件已存在于数据库中"。
但是我做了一个call_back功能来检查电子邮件是否已更改。
但是,它不起作用。
我的控制器:保存,call_back控制器:
public function save() {
$uid = $this->uri->segment(4);
$this->load->library('form_validation');
//Initial checks: mistakes to look out for. For eg. username too long, etc.
$this->form_validation->set_rules('first_name', 'First Name', 'required|trim|min_length[3]|max_length[20]|xss_clean|alpha_numeric');
$this->form_validation->set_rules('last_name', 'Last Name', 'required|trim|min_length[3]|max_length[20]|xss_clean|alpha_numeric');
$this->form_validation->set_rules('username', 'Username', 'required|trim|min_length[3]|max_length[20]|callback__is_unique_username[username]|xss_clean|alpha_numeric');
$this->form_validation->set_rules('email', 'Email', 'required|trim|min_length[6]|max_length[50]|valid_email|callback__is_unique_email[email]|xss_clean');
$this->form_validation->set_message('_is_unique_email', '%s already exists');
if ($this->form_validation->run() == FALSE) {
//user didn't validate, send back to login form and show errors
} else {
//successful update
if ($result) {
//do something
} else {
//do something
}
}
}
//----FUNCTION TO CHECK IF EMAIL IS ALREADY IN DATABASE WHEN USER UPDATES----/
public function _is_unique_email($value, $field)
{
$result = $this->db->where('uid !=', $this->session->userdata('uid'))
->where($field, $value)
->get('users')
->row_array();
if ($result) {
$this->form_validation->set_message('_is_unique_email', 'The %s already exists in database.');
return false;
}
return true;
}
//check if username is unique
public function _is_unique_username($value, $field)
{
$result = $this->db->where('uid !=', $this->session->userdata('uid'))
->where($field, $value)
->get('users')
->row_array();
if ($result) {
$this->form_validation->set_message('_is_unique_username', 'The %s already exists in database.');
return false;
}
return true;
}
这可能会对你有所帮助。
验证规则:
$this->form_validation->set_rules('username', 'Username', 'required|trim|min_length[3]|max_length[20]|callback_is_unique_username|xss_clean|alpha_numeric');
$this->form_validation->set_rules('email', 'Email', 'required|trim|min_length[6]|max_length[50]|valid_email|callback_is_unique_email|xss_clean');
回调功能:
public function is_unique_email($email)
{
$result = $this->db->where('uid !=', $this->session->userdata('uid'))
->where('email_address', $email) // Column Name to be checked
->get('users');
if ($result->num_rows() > 0) {
$this->form_validation->set_message('is_unique_email', 'The %s already exists in database.');
return false;
}
return true;
}