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'));
  }
}

Comments

Elijah Lynn’s picture

How would I use these to accept both US and UK phone numbers?

-----------------------------------------------
The Future is Open!

Anandyrh’s picture

Good question,

I like to know about India as well

g1smd’s picture

The UK pattern is way too simplistic and broad. The UK telephone number in national format will always begin with 0, and the next digit will never be 0, 4 or 6.

Only certain ranges are valid as listed at:
http://www.aa-asterisk.org.uk/index.php/Number_format and
http://www.aa-asterisk.org.uk/index.php/Regular_Expressions_for_Validati...

bzj00220’s picture

I need your help please tell me
I like to know about japan as well

jjones150’s picture

Where would this code be implemented for a form that I used drupal to build. That is, I added fields specific to my site by going to configuration-->Account Settings-->Manage Fields tab to add additional fields. So, where would I use this code for say, phone number validation, without altering core drupal?

Any help is greatly appreciated.