Drupal - E-mail validation form api

Create a validation function for your form. Here is an example using your form. For instance, say your form code is in a function called my_email:

<?php
function my_email() {
  $form = array();

  $form['address']['mail'] = array(
   '#type' => 'textfield',
   '#title' => t('E-mail'),
   '#required' => TRUE,
   '#default_value' => $subscription->mail,
   '#maxlength' => 255,
  ); 

  $form['submit'] = array(
   '#type' => 'submit',
   '#value' => t('Versturen'),
  );

  return $form;
}

function my_email_validate($form, &$form_state) {
  // YOUR CUSTOM VALIDATION CODE GOES HERE
 if (!valid_email_address($mail)) {
   form_set_error('submitted][email_address', t('The email address appears to be invalid.'));
   }
}

function my_email_submit($form, &$form_state) {
  // YOUR CUSTOM SUBMIT CODE GOES HERE
}
?>

This function will allow you to write custom code to determine if the values entered in your fields are valid or not. You can also add a custom submit function for your form to execute custom code while the form is being submitted.

Read more about validating forms at Validating Forms, submitting forms at Submitting Forms or read the whole article for a better understanding of the Forms API: Form API Quickstart Guide


Instead of adding a form validation handler to the form, you can add a validation handler to the form element that needs to be validated: Use #element_validate, which accepts an array of validation handlers that will be applied to the form element.

$form['email'] = array(
  '#type' => 'textfield',
  '#title' => 'Email',
  '#required' => TRUE,
  '#element_validate' => array('myelement_email_validate')
);

The validation handler receives three arguments: The form element being validated, the $form_state and the $form array for the form containing the form element. The validation handler should call form_error() or form_set_error() to report any validation error.

function myelement_email_validate($element, &$form_state, $form) {
  $value = $element['#value'];
  if (!valid_email_address($value)) {
    form_error($element, t('Please enter a valid email address.'));
  }
}

Explained here: http://drupal.org/node/279127

<?php
$mail = $form_values['submitted_tree']['email_address'];
if (!valid_email_address($mail)) {
  form_set_error('submitted][email_address', t('The email address appears to be invalid.'));
}
?>

Tags:

Forms