Проверка номера телефона на валидность python

I’m trying to validate a mobile number, the following is what I have done so far, but it does not appear to work.

I need it to raise a validation error when the value passed does not look like a mobile number. Mobile numbers can be 10 to 14 digits long, start with 0 or 7, and could have 44 or +44 added to them.

def validate_mobile(value):
    """ Raise a ValidationError if the value looks like a mobile telephone number.
    """
    rule = re.compile(r'/^[0-9]{10,14}$/')

    if not rule.search(value):
        msg = u"Invalid mobile number."
        raise ValidationError(msg)

SuperStormer's user avatar

SuperStormer

4,8625 gold badges23 silver badges34 bronze badges

asked Apr 21, 2013 at 19:04

GrantU's user avatar

5

I would recommend to use the phonenumbers package which is a python port of Google’s libphonenumber which includes a data set of mobile carriers now:

import phonenumbers
from phonenumbers import carrier
from phonenumbers.phonenumberutil import number_type

number = "+49 176 1234 5678"
carrier._is_mobile(number_type(phonenumbers.parse(number)))

This will return True in case number is a mobile number or False otherwise. Note that the number must be a valid international number or an exception will be thrown. You can also use phonenumbers to parse phonenumber given a region hint.

answered Feb 6, 2014 at 16:22

davidn's user avatar

davidndavidn

7827 silver badges13 bronze badges

4

The following regex matches your description

r'^(?:+?44)?[07]d{9,13}$'

answered Apr 21, 2013 at 19:11

MikeM's user avatar

MikeMMikeM

13k2 gold badges32 silver badges47 bronze badges

2

I would try something like:

re.compile(r'^+?(44)?(0|7)d{9,13}$')

You would want to first remove any spaces, hyphens, or parentheses though.

answered Apr 21, 2013 at 19:09

dgel's user avatar

dgeldgel

16.1k8 gold badges58 silver badges75 bronze badges

1

These won’t validate +44 numbers as required. Follow update: John Brown’s link and try something like this:

def validate_not_mobile(value):

    rule = re.compile(r'(^[+0-9]{1,3})*([0-9]{10,11}$)')

    if rule.search(value):
        msg = u"You cannot add mobile numbers."
        raise ValidationError(msg)

answered Apr 21, 2013 at 20:00

Glyn Jackson's user avatar

Glyn JacksonGlyn Jackson

8,2084 gold badges27 silver badges52 bronze badges

3

import phonenumbers
from phonenumbers import carrier, timezone, geocoder
from phonenumbers.phonenumberutil import number_type

number = "+911234567890"
print(carrier._is_mobile(number_type(phonenumbers.parse(number))))
print(phonenumbers.parse("+911234567890"))

my_number = phonenumbers.parse("+911234567890")
print(carrier.name_for_number(my_number, "en"))

print(timezone.time_zones_for_number(my_number))

print(geocoder.description_for_number(my_number, "en"))

print(phonenumbers.is_valid_number(my_number))
print(phonenumbers.is_possible_number(my_number))

The reason is that the is_possible_number() method makes a quick guess on the phone number’s validity by checking the length of the parsed number, while the is_valid_number() method runs a full validation by checking the length, phone number prefix, and region.

answered Nov 5, 2021 at 6:26

MRUNAL MUNOT's user avatar

MRUNAL MUNOTMRUNAL MUNOT

3871 gold badge5 silver badges18 bronze badges

You can create a validate function using phonenumbers package

for example:

import phonenumbers

def validate_phone_number(potential_number: str, country_code: str) -> bool:
    try:
        phone_number_obj = phonenumbers.parse(potential_number, country_code)
    except phonenumbers.phonenumberutil.NumberParseException:
        return False
    if not phonenumbers.is_valid_number(phone_number_obj):
        return False
    return True

answered Dec 18, 2022 at 13:58

Alon Barad's user avatar

Alon BaradAlon Barad

1,3151 gold badge13 silver badges23 bronze badges

Python validation mobile number for sololearn

str = input()
import re
if len(str)==8:
   pattern=r"[981][^.......$]"  
   match = re.match(pattern,str) 
   if match: 
      print("Valid")
   else:
      print("Invalid")
else:
   print("Invalid")

answered Jan 7, 2021 at 8:46

Jupanu's user avatar

1

In this tutorial, it’s shown how to find and validate phone numbers in Python using simple examples. We will review different phone number formats which are the most popular.

The best option for search and validation of data like phones numbers, zip codes, identifiers is Regular expression or Regex.

Next, we’ll see the examples to find, extract or validate phone numbers from a given text or string. The article starts with easy examples and finishes with advanced ones.

Step 1: Find Simple Phone Number

Let’s suppose that we need to validate simple phone number formats which don’t change. For example:

  • 000-000-000
re.findall(r"[d]{3}-[d]{3}-[d]{3}", text)
  • 000 000 0000
re.findall(r"[d]{3} [d]{3} [d]{3}", text)

The goal is to find all matches for the pattern.
The mentioned solution is very basic and it’s not working for numbers like:

  • 9000-000-0009 — it will find only 000-000-000
  • 000 000 000
  • (000)000-000

In order to deal with those cases the Regex should be improved.

Step 2: Regex for Phone Numbers with a Plus

Often phones numbers are displayed with plus sign like:

  • +000-000-000

This format is matched by next regular expression:

re.findall(r"+?[d]{3}-[d]{3}-[d]{3}", text)

Note that this will catch:

  • 000-000-000
  • +000-000-000

but also:

5000-000-0004 will be extracted as 000-000-000. In the next step we will solve this problem.

Step 3: Validate Phone Numbers for Exact Match

If the the format is important and only exact matches are needed like:
000-000-000, +000-000-000 but not — 5000-000-0004 , +000-000-0004 then we need to add word boundaries to our Regex by adding at the start and the end b:

re.findall(r"+?b[d]{3}-[d]{3}-[d]{3}b", text)

Next let’s see a more generic example which covers international and country phone numbers.

Step 4: Validate International Phone Number

It’s difficult to find and test international numbers with 100% accuracy. Analysis of the data might be needed in order to check what formats are present in the text.

One possible solution for validation of international numbers is:

re.match(r"^[+(]?d+(?:[- )(]+d+)+$", phone)

Another regular expression is:

re.match(r"^[+d]?(?:[d-.s()]*)$", phone)

Step 4: Validate US, UK, French phone numbers

For example let’s start with US phone numbers:

  • (000)000-0000
  • 000-000-0000
  • (000) 000-0000

can be done with next Regex:

re.match(r"^(([0-9]{3}) ?|[0-9]{3}-)[0-9]{3}-[0-9]{4}$", phone)

UK or GB numbers like:

  • +447222000000
  • +44 7222 000 000

can be searched and validated by:

^(?:0|+?44)s?(?:ds?){9,11}$

other possible solution for UK is: ^(+44s?7d{3}|(?07d{3})?)s?d{3}s?d{3}(s?#(d{4}|d{3}))?$

The next simple Regex will work for French numbers:

^(?:(?:+|00)33|0)s*[d](?:[s.-]*d{2}){4}$

like:

  • 00 00 00 00 00
  • +33 0 00 00 00 00

Step 5: Find phone numbers in different formats

If you like to build a Regex which find various formats you can try with the next one:

[+d]?(d{2,3}[-.s]??d{2,3}[-.s]??d{4}|(d{3})s*d{3}[-.s]??d{4}|d{3}[-.s]??d{4})

The one above will cover most phone numbers but will not work for all.

If the validation is important or additional features are needed like:

  • updates for new formats/countries/regions
  • geographical information related to a phone number
  • timezone information

then we will recommend mature libraries to be used. Good example in this case is the Google’s Java and JavaScript library for parsing, formatting, and validating international phone numbers.

Conclusion

Have in mind that Regex are powerful but you may face performance issues for the complex ones. Try to use simple and understandable Regex. Sometimes you may need to play with flags in order to make it work properly:

/^[(]?0([d{9})$/mg

Another important note is about using:

  • start and end — ^ and $
  • word boundaries — b

We covered most cases of phone validation by using python and Regex.

  • #1

У меня есть строка, в которой хранится номер телефона. Мне надо проверить, соответствует ли данная строка регулярному вырежению ^((+?7|8)[ -] ?)?(((d{3}))|(d{3}))?([ -])?(d{3}[- ]?d{2}[- ]?d{2})$

  • #2

Python:

import re

a = '8-900-800-10-20'
r = re.compile('^((+?7|8)[ -] ?)?(((d{3}))|(d{3}))?([ -])?(d{3}[- ]?d{2}[- ]?d{2})$')

if r.search(a):
    print('соответствует')
else:
    print('не соответствует')

  • #3

Python:

import re

a = '8-900-800-10-20'
r = re.compile('^((+?7|8)[ -] ?)?(((d{3}))|(d{3}))?([ -])?(d{3}[- ]?d{2}[- ]?d{2})$')

if r.search(a):
    print('соответствует')
else:
    print('не соответствует')

А данная регулярка подходит для проверки номера в python? Я ввожу 8916202 и у меня всё принимается

  • #4

А данная регулярка подходит для проверки номера в python? Я ввожу 8916202 и у меня всё принимается

это проблема с регуляркой…
попробуйте такую

Код:

r = re.compile('^+7|8D*d{3}D*d{3}D*d{2}D*d{2}')

  • #5

вот такая лучше

Python:

r = re.compile('(+7|8)D*d{3}D*d{3}D*d{2}D*d{2}')

  • #6

Всё получилось, спасибо. А регулярку для номера авто не подскажите?

Последнее редактирование: Мар 21, 2021

  • #9

так можно

Python:

r = re.compile('[а-я]{1}d{3}[а-я]{2}d{2}[а-я]{3}')

в номерах не все буквы используются вроде, можно в квадратных скобках их указать вместо а-я…

Это тоже интересно:

  • Программа где можно проверить номер телефона
  • Проверка номера телефона звонящего
  • Программа для замены номеров телефонов
  • Программа антисон номер телефона
  • Программа для замены номера телефона при звонке

  • Понравилась статья? Поделить с друзьями:
    0 0 голоса
    Рейтинг статьи
    Подписаться
    Уведомить о
    guest

    0 комментариев
    Старые
    Новые Популярные
    Межтекстовые Отзывы
    Посмотреть все комментарии