Use Drupal's built-in email validation function for custom form email field

Public

Use Drupal's built-in email validation function for custom form email field

</> CopyGet raw version
php
  1. function test_menu() {
  2.  
  3. $items['test'] = array(
  4. 'title' => t('Email Field Validation'),
  5. 'page callback' => 'drupal_get_form',
  6. 'page arguments' => array('test_custom_form',1),
  7. 'access arguments' => array('access content'),
  8. //'file' => 'test.inc',
  9. //'file path' => drupal_get_path('module', 'test') . '/includes',
  10. );
  11. return $items;
  12. }
  13.  
  14. function test_custom_form($form, $form_state) {
  15.  
  16. $form = array();
  17. $form['email'] = array(
  18. '#type' => 'textfield',
  19. '#title' => 'Email',
  20. '#prefix' => '<div id="email-field-wrapper">',
  21. '#suffix' => '</div>',
  22. '#required' => TRUE,
  23. );
  24. $form['submit_form'] = array(
  25. '#type' => 'submit',
  26. '#value' => t('Next'),
  27. '#submit' => array('test_custom_form_submit'),
  28. );
  29. $form['#validate'] = array('test_custom_form_validation');
  30. return $form;
  31. }
  32.  
  33. function test_custom_form_validation($form, &$form_state) {
  34. $mail = $form_state['values']['email'];
  35. if (!valid_email_address($mail)) {
  36. form_set_error('email', t('Please Enter a valid email address.'));
  37. }
  38. }
  39.  
  40. function test_custom_form_submit($form, &$form_state) {
  41. drupal_set_message("form is submitted, thanks");
  42. }

Comments

marcvangend's picture

Be aware that valid_email_address() regards someone@example as a valid email address. While this is technically correct (after all "localhost" is a valid domain name) you may want to implement another regex which requires at least one dot in the domain name.

leigh's picture

Line 29 isn't needed either you could have just called your validation function test_custom_form_validate($form, &$form_state) and it would have been used automatically

swapnil phadke's picture

how to validate email id. i write your code but not work for me??

swapnilphadke's picture

not working code.plz give me right code