Support for Drupal 7 is ending on 5 January 2025—it’s time to migrate to Drupal 10! Learn about the many benefits of Drupal 10 and find migration tools in our resource center.
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
How would I use these to
How would I use these to accept both US and UK phone numbers?
-----------------------------------------------
The Future is Open!
Good question, I like to know
Good question,
I like to know about India as well
UK telephone number format.
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...
I need your help please tell
I need your help please tell me
I like to know about japan as well
Use with Standard Form
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.