Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python validation mobile number

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)
like image 633
GrantU Avatar asked Apr 21 '13 19:04

GrantU


People also ask

How do I validate a mobile number?

Mobile Number validation criteria:The first digit should contain numbers between 6 to 9. The rest 9 digit can contain any number between 0 to 9. The mobile number can have 11 digits also by including 0 at the starting. The mobile number can be of 12 digits also by including 91 at the starting.

How do you input a phone number in Python?

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.

How does Django validate phone numbers in Python?

You need to make modifications eithe to your is_valid_number(z) or to your z variable by adding the code yourself in front of the number before validation. Provide your is_valid_number(z) function to help you more. You should call your method clean_phone_number() otherwise it won't be called.

How do you mask a phone number in Python?

Navigate to the Numbers page and select the phone number you want to use for this application. From the Application Type drop-down, select XML Application . From the Plivo Application drop-down, select Number Masking (the name we gave the application). Click Update Number to save.


2 Answers

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.

like image 200
davidn Avatar answered Sep 20 '22 02:09

davidn


The following regex matches your description

r'^(?:\+?44)?[07]\d{9,13}$'
like image 20
MikeM Avatar answered Sep 20 '22 02:09

MikeM