How do I validate a mobile number using Python?

Question:

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)
Asked By: GrantU

||

Answers:

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 By: dgel

The following regex matches your description

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

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 By: Glyn Jackson

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 By: davidn

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 By: Jupanu
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 By: MRUNAL MUNOT

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 By: Alon Barad
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.