Main menu

E-mail domain name Drupal's built-in validation

Published by dnovikov on Mon, 02/21/2011 - 14:02

Generally speaking, there is a plenty of issues about the emails validation and valid_email_address function on I'm not going to discuss neither its RFC compliance nor implementation. For me, there is only one issue with this function: it allows domain names without a dot. It accepts, for example, mail@localhost or mail@gmailcom. Not malicious itself such behavior sometimes is very undesirable, especially if you're working with something like paid subscriptions. A user subscribes, system accepts his email, but what if he has mispelled and forgot this damn small "."? A fix of this problem is very simple, but I want to publish it... maybe it can save you from typing (well, not totally) and wasting valuable time.

The trick is done inside the hook_form_alter hook. Add another validation function to a form:

switch($form_id) {
$form['#validate'][] = 'yourmodule_user_register_validate';

function yourmodule_user_register_validate($form, &amp;$form_state) {
  if (!
preg_match('/^.*\.\w{1,3}$/', $form_state['values']['mail'])) {
form_set_error('mail', t('Invalid e-mail address.'));

The same thing could be done for any places where users can submit their emails: user profile, subscription page, other forms and pages.

Add new comment

Plain text

  • No HTML tags allowed.
  • Web page addresses and e-mail addresses turn into links automatically.
  • Lines and paragraphs break automatically.
By submitting this form, you accept the Mollom privacy policy.