Проверка ввода номера телефона 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.

Not sure of the exact format you want but using a regex would probably be easier:

import  re
s ="043-4443-344"
n = re.match("^d+-d+-d+$",s)
if n:
    print(n.group())

"^d+-d+-d+$" will match a string starting with one or more digits followed by a hyphen, one or more digits followed by a hyphen and ending with one or more digits. If you want to allow a specific amount of digits you can use, for example ^d{3,5} to make the area code be between 3-5 digits long.

Your first check should probably be if len(phone_number) != 12 as there is no point going any further if it is not.

If you want to do it without a regex then you can do something like the following:

def valid_telephone_number(inp):
    # make sure len is 12 and all char at index 3 and 7  are -
    if not all(inp[x] == "-" for x in [3,7])and len(inp) == 12:
        return False
    # will be True if all that is left are digits after removing the - else False
    return inp.replace("-", "", 3).isdigit()



def main():
    while True:
        phone_number = input('Enter your telephone number: ')
        check = valid_telephone_number(phone_number)
        # will be True for a valid num so return the formatted input
        if check:
            return check
        # or else print message telling use the input was invalid and ask again
        print('{} is a not valid entry, please try again.'.format(phone_number))

Not sure of the exact format you want but using a regex would probably be easier:

import  re
s ="043-4443-344"
n = re.match("^d+-d+-d+$",s)
if n:
    print(n.group())

"^d+-d+-d+$" will match a string starting with one or more digits followed by a hyphen, one or more digits followed by a hyphen and ending with one or more digits. If you want to allow a specific amount of digits you can use, for example ^d{3,5} to make the area code be between 3-5 digits long.

Your first check should probably be if len(phone_number) != 12 as there is no point going any further if it is not.

If you want to do it without a regex then you can do something like the following:

def valid_telephone_number(inp):
    # make sure len is 12 and all char at index 3 and 7  are -
    if not all(inp[x] == "-" for x in [3,7])and len(inp) == 12:
        return False
    # will be True if all that is left are digits after removing the - else False
    return inp.replace("-", "", 3).isdigit()



def main():
    while True:
        phone_number = input('Enter your telephone number: ')
        check = valid_telephone_number(phone_number)
        # will be True for a valid num so return the formatted input
        if check:
            return check
        # or else print message telling use the input was invalid and ask again
        print('{} is a not valid entry, please try again.'.format(phone_number))

Python is a very powerful language and also very rich in libraries. phonenumbers is one of the modules that provides numerous features like providing basic information of a phone number, validation of a phone number etc. Here, we will learn how to use phonenumbers module just by writing simple Python programs. This is a Python port of Google’s libphonenumber library.

Installation

Install the phonenumbers module by typing the following command in command prompt.

pip install phonenumbers

Getting Started

1. Convert String to phonenumber format: To explore the features of phonenumbers module, we need to take the phone number of a user in phonenumber format. Here we will see how to convert the user phone number to phonenumber format. Input must be of string type and country code must be added before phone number.

Python3

import phonenumbers

phoneNumber = phonenumbers.parse("+919876543210")

print(phoneNumber)

Output:

Country Code: 91 National Number: 9876543210

2. Get Timezone: Here is the simple Python program to get the timezone of a phone number using phonenumbers module. First, we do parse the string input to phonenumber format, and then we use an inbuilt function to get the timezone of a user. It gives the output for valid numbers only.

Python3

import phonenumbers

from phonenumbers import timezone

phoneNumber = phonenumbers.parse("+919876543210")

timeZone = timezone.time_zones_for_number(phoneNumber)

print(timeZone)

Output:

('Asia/Calcutta',)

3. Extract phone numbers from text: We can extract phone numbers that are present in a text/paragraph using this module. You can iterate over it to retrieve a sequence of phone numbers. For this, PhoneNumberMatcher object provides the relevant function.

Python3

import phonenumbers

text = "Contact us at +919876543210 or +14691234567"

numbers = phonenumbers.PhoneNumberMatcher(text, "IN")

for number in numbers:

    print(number)

Output:

PhoneNumberMatch [14,27) +919876543210

4. Carrier and Region of a Phone Number: Here we will learn how to find the carrier and region of a phone number using the geocoder and carrier functions of this module.

Python3

import phonenumbers

from phonenumbers import geocoder, carrier

phoneNumber = phonenumbers.parse("+919876543210")

Carrier = carrier.name_for_number(phoneNumber, 'en')

Region = geocoder.description_for_number(phoneNumber, 'en')

print(Carrier)

print(Region)

Output:

Airtel
India

5. Validation of a phone number: A simple python program, to check whether a given phone number is valid or not (e.g. it’s in an assigned exchange), and to check whether a given phone number is possible or not (e.g. it has the right number of digits).

Python3

import phonenumbers

phone_number = phonenumbers.parse("+91987654321")

valid = phonenumbers.is_valid_number(phone_number)

possible = phonenumbers.is_possible_number(phone_number)

print(valid)

print(possible)

Output:

False
True

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

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

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

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