Python验证手机号码

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/16135069/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-18 21:50:45  来源:igfitidea点击:

Python validation mobile number

pythonregexdjango

提问by GrantU

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

我正在尝试验证手机号码,以下是我迄今为止所做的,但似乎不起作用。

I need it to rise 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.

当传递的值看起来不像手机号码时,我需要它来引发验证错误。手机号码可以是 10 到 14 位数字,以 0 或 7 开头,并且可以添加 44 或 +44。

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)

采纳答案by MikeM

The following regex matches your description

以下正则表达式符合您的描述

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

回答by dgel

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.

不过,您可能需要先删除所有空格、连字符或括号。

回答by Glyn Hymanson

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

这些不会按要求验证 +44 号码。按照 更新:约翰布朗的链接并尝试这样的事情:

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)

回答by davidn

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

我建议使用phonenumbers包,它是 Google 的 libphonenumber 的 python 端口,它现在包含移动运营商的数据集:

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 phonenumbersto parse phonenumber given a region hint.

如果 number 是手机号码,这将返回 True,否则返回 False。注意号码必须是有效的国际号码,否则会抛出异常。您还可以使用电话号码来解析给定区域提示的电话号码。