Similar contents

Tag: Change the form validation message using Hook in Drupal

Change the form validation message using Hook in Drupal

Using Hook you can customize the message from forms like user_login_form, user_register_form and etc

By

pablito

created on Sunday, January 14, 2024 - 02:44AM - UTC

Content body

In this example I'll give you a simple and straightforward way of using the hook_form_FORM_ID_alter, and in a future post I'll give you a way of overwriting it using OOP.

In this case, we're talking about these messages, more specifically the email message I'm about to exemplify.

user register form

 

Change the error message by Hook

On your custom module, file .module, since we've already identified the form id using this hook, we don't need to validate it again. In this example we change the email, but feel free  to change any other fields.
I've split it into a separate function because it's a good practice for reuse, just for that reason.

 
/**
* Implements hook_form_FORM_ID_alter() for the user_register_form form.
*/
function custom_module_form_user_register_form_alter(&$form, &$form_state, $form_id) {
  // Add custom validation function to validate email.
  $form['account']['mail']['#element_validate'][] = '_custom_module_validate_email';
 
}
 
/**
* Custom validation function to check email on user registration.
*/
function _custom_module_validate_email(&$form, &$form_state) {
  $email = $form_state->getValue('mail');
  // Validate email format.
  if (!\Drupal::service('email.validator')->isValid($email)) {
    $form_state->setErrorByName(
      'mail',
      t('Custom message: %mail is not valid :( try another one!', ['%mail' => $email])
    );
  }
 
  // Check if email is already registered.
  $users = \Drupal::entityTypeManager()->getStorage('user')->loadByProperties(['mail' => $email]);
  $account = reset($users);
  if ($account) {
    $form_state->setErrorByName(
      'mail',
      t('Custom message: The %mail is already registered :(', ['%mail' => $email])
    );
  }
}
 

Tks!!

More content for you

Join the conversation

Plain text

  • No HTML tags allowed.
  • Lines and paragraphs break automatically.
  • Web page addresses and email addresses turn into links automatically.
keyboard_arrow_up