I have an update page for my users where they can edit their name, email and other info.
So far, they can edit everything. Including their email. They can enter an e
Your Javascript file:
$("#form_id").validate({
rules: {
email: {
required: true,
email: true,
remote: {
type: "post",
url: "pathtocontroller/controller.php/checkEmail",
}
}
},
messages: {
email: {
required: "Please enter Email!",
email: "Please enter valid Email!",
remote: "Email already not available!"
}
}
Your Controller File:
function checkEmail() {
$userArr = $this->input->post();
$id = $this->session->userdata('id');//if you have stored id within session else pass it within remote function
if (isset($userArr["email"])) {
if ($id != '') {
$ext_cond = "id !='" . $id . "'";
}
echo $this->your_model_name->getUserValidation('your_email_field_name', $userArr['email'], $ext_cond);
exit;
}
exit;
}
Your Model:
public function getUserValidation($usertype = '', $value = '', $cond = '') {
if ($usertype != '' && $value != '') {
$this->db->select($usertype);
$this->db->from($this->main_table);
if ($cond != '') {
$this->db->where($cond);
}
if (is_array($usertype)) {
foreach ($usertype as $key => $type_value) {
$this->db->where($type_value, $value[$key]);
}
} else {
$this->db->where($usertype, $value);
}
$user_data = $this->db->get()->result_array();
// echo $this->db->last_query();exit;
if (is_array($user_data) && count($user_data) > 0) {
return "false";
} else {
return "true";
}
} else {
return "false";
}
}
use validate library : http://docs.jquery.com/Plugins/Validation/Methods/remote
your javascript :
$("#yourFormId").validate({
rules: {
email: {
required: true,
email: true,
remote: {
url: "checkmail.php",
type: "post"
}
}
},
messages: {
email: {
required: "Please Enter Email!",
email: "This is not a valid email!",
remote: "Email already in use!"
}
}
});
checkmail.php:
<?php
$registeredEmails = array('test1@test.com', 'test2@test.com', 'test3@test.com');
$requestedEmail = $_POST['email'];
if( in_array($requestedEmail, $registeredEmails) ){
echo 'false';
}
else{
echo 'true';
}
?>
if you use codeigniter means use checkmail.php as a controller function.. you can pass your $registeredEmails array values as $registeredEmails[] = "your query result which is in for loop".
You can try the following code :
$this->form_validation->set_rules('email', 'lang:email', 'trim|required|valid_email|callback__is_unique_email[email]');
and the callback function should look like this :
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', $this->lang->line('_is_unique_'));
return false;
}
return true;
}