Validating a Phone Number

Last updated on
30 April 2025

United States Phone Number Validation

This generic phone number validation snippet requires phone numbers to be separated by hyphens. A country code is required.

  $phone = $form_values['submitted_tree']['phone'];
  if (strlen($phone) > 0 && !preg_match('/^[0-9]{1,3}-[0-9]{3}-[0-9]{3,4}-[0-9]{3,4}$/', $phone)) {
    form_set_error('submitted][phone', t('Phone number must be in format xxx-xxx-nnnn-nnnn.'));
  }

United Kingdom Phone Number Validation

Note: This following example is for DRUPAL-5. For DRUPAL-6, you need to change form_values to form_state.

$phone = $form_values['submitted_tree']['phone'];
if (strlen($phone) > 0) {
  $phone = str_replace (' ', '', $phone);
  $phone = str_replace ('-', '', $phone);
  $phone = str_replace ('(', '', $phone);
  $phone = str_replace (')', '', $phone);
  $phone = str_replace ('[', '', $phone);
  $phone = str_replace (']', '', $phone);
  $phone = str_replace ('{', '', $phone);
  $phone = str_replace ('}', '', $phone);

  if (preg_match('/^(\+)[\s]*(.*)$/',$phone)) {
    form_set_error('submitted][phone', t('UK telephone number without the country code, please'));
  }
  if (!preg_match('/^[0-9]{10,11}$/',$phone)) {
    form_set_error('submitted][phone', t('UK telephone numbers should contain 10 or 11 digits'));
  }
  if (!preg_match('/^0[0-9]{9,10}$/',$phone)) {
    form_set_error('submitted][phone', t('The telephone number should start with a 0'));
  }
}

Help improve this page

Page status: Not set

You can: