0

I have created a custom form as below. And the user has to fill all the fields for the submission(I am storing all the fields after submission).

Question is how do i check if the email address has already been entered ?

enter image description here

2

One way of doing that is using the hook_form_alter and add the custom validation function, and in that custom validation you can check if the enterd email already exists in the database than set error, somewhat like below:

/**
 * Implements hook_form_alter.
 */
function MYMODULE_form_alter(&$form, &$form_state, $form_id) {
  // Check the form id of your form.
  if ($form_id === 'YOUR_FORM_ID_WHICH_YOU_WANT_TO_EDIT') {
    $form['#validate'][] = 'check_email_address_exists';
  }
}

function check_email_address_exists(&$form, &$form_state) {
  // Get the value of email field. if you are under than use: "dpm($form_state['values'])"
  $email_entered = $form_state['values']['EMAIL_FIELD_NAME'];

  // Generate the query somewhat like below, For Example I am using users table's "uid".
  $query = db_select('users', 'u');
  $query->fields('u', array('uid'));
  $query->condition('u.mail', $email_entered);

  // This will return the count of the fields found.
  $row_count = $query->countQuery()->execute()->fetchField(); 

  if (isset($row_count) && ($row_count > 0)) {
    form_set_error('EMAIL_ADDRESS_FIELD_NAME', t('This email already exists, please try with another email  address!'));
  }
}

In order it to work you have to change the values as per you requirement, and don't forget to modify the db_select query as per your requirement, and last CLEAR THE CACHE after implementing the same.

  • No need to use alter when he is the one who created the form in the first place. – Mołot Oct 22 '13 at 12:56
  • Yeah right if one has created the custom form than the validation can be added directly instead of using the hook_form_alter, otherwise we can use hook_form_alter to add the custom validator. :) – Ankit Agrawal Oct 22 '13 at 12:59

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.