Create a gist now

Instantly share code, notes, and snippets.

What would you like to do?
Drupal 8 - Allow login by email
* Implements hook_form_alter().
function MODULE_form_user_login_form_alter(&$form, \Drupal\Core\Form\FormStateInterface $form_state) {
// Allow login with email.
array_unshift($form['#validate'], 'MODULE_user_login_form_validate');
// Change the field label.
$form['name']['#title'] = new \Drupal\Core\StringTranslation\TranslatableMarkup('Email or Username');
* Callback to check for a valid email for login.
function MODULE_user_login_form_validate(array &$form, \Drupal\Core\Form\FormStateInterface $form_state) {
if (!$form_state->isValueEmpty('name') && \Drupal::service('email.validator')->isValid($form_state->getValue('name'))) {
// Try to find a user name for this email.
if ($user = user_load_by_mail($form_state->getValue('name'))) {
$form_state->setValue('name', $user->getUsername());
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment