I am looking for a concrete way to only allow logging in with email address only in Drupal 8.
I have seen Login Email and Login EmailUsername modules, but both still allow for username login as well as email.
I am looking only for email.
So far, I have come up with this in the interim - but something is not quite right. While I can trigger a form error, the form still submits and authentication is called. It should not submit if the entered value does not resemble an email address:
/**
* Implements hook_form_FORM_ID_alter().
*/
function mymodule_form_user_login_form_alter(&$form, FormStateInterface $form_state) {
$form['name']['#type'] = 'email';
$form['name']['#title'] = t('Email Address');
$form['name']['#description'] = t('Enter your email address.');
$form['name']['#element_validate'][] = 'mymodule_login_validate_user';
$form['pass']['#description'] = t('Enter the password that accompanies your email address.');
}
/**
* Custom validation handler for the form login.
*
* @param $form
* @param $form_state
* @return bool
*/
function mymodule_login_validate_user(&$element, FormStateInterface $form_state) {
$email_input = $form_state->getValue('name');
if (!\Drupal::service('email.validator')->isValid($email_input)) {
$form_state->setError($element, 'Please enter a valid email address.');
}
}
I am also overriding the core user.auth
service with my own - I will be generating usernames based on factors about the user (fetching information from a remote AMS).
Is there any way to avoid username in Drupal 8?
edit: Users cannot register on the Drupal site, and forgot password will be replaced with a link to the external AMS system.
$form['name']['#element_validate'][]
never seen it done like this before, the way I know its:$form['#validate'][] = 'mymodule_login_validate_user';
and remove the&$element
param from your call back function.function mymodule_login_validate_user($form, FormStateInterface $form_state) {
email_registration
module was still enabled (was checking it out) causing me trouble. I am providing my own UserAuth service, so now with just the above, only email login is allowed.