How do I validate a mobile number using Python?

django, python, regex

Solution

The following regex matches your description

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

Problem

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) ```

Original source