I am using the form API to create forms. How can I validate the email address without needing any separate module? I am just looking for out of the box functionality.

  • There isn't anything out of the box, you'll either need a custom or contributed module, or to implement hook_form_alter() in your theme's template.php file – Clive Nov 26 '14 at 23:30

In a custom module, consider using PHP's built function for email validation: filter_var().

$email_a = 'joe@example.com';
$email_b = 'bogus';

if (filter_var($email_a, FILTER_VALIDATE_EMAIL)) {
    echo "This ($email_a) email address is considered valid.";
if (filter_var($email_b, FILTER_VALIDATE_EMAIL)) {
    echo "This ($email_b) email address is considered valid.";

This code will go into a validation function. A validation function can be added as an element to the form array (see the form API for details) that you linked to. If your module is named spade, for example, your form may be in function spade_form(). Your submit may then be put in function spade_form_submit(), and your validation would be in function spade_form_validate(). This is the default handler for validation.

See the following links for more information.

The first example is exactly what you're looking for (and the example that I copied above). The last link contains the examples module, which has a lot of great form examples.

| improve this answer | |

Out of the box the form API for Drupal 7 has the functions listed in https://api.drupal.org/api/drupal/includes%21form.inc/7, which includes element_validate_integer(), element_validate_number() and element_validate_positive_integer() for textfields.

You are free to provide your own element validate function for any form element you wish to provide custom code for, which is not provided by Drupal Core. You do this by providing an #element_validate key and creating the custom function. see the official form API documents on #element_validate.

You can also give in, and install the Email field module.

| improve this answer | |

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.