python正则表达式删除所有非数字字符并确保phone numb有效

2024-07-05 08:51:02 发布

您现在位置:Python中文网/ 问答频道 /正文

我想把我所有的电话号码验证移到一个django验证字段中。如何使用这个phone number验证器包含字符串中的所有非数字字段?你知道吗

例如,“123.123.1234”将变为“1234”

我知道你可以用一个替换,比如replaceAll( "[^\\d]", "" ),但是它必须是django验证器的一个regex

validate_phone_number = RegexValidator(
    regex=re.compile(r'^\+?1?\d{9,15}$'),
    message="Phone number must be entered in the format: '+999999999'. Up to 15 digits allowed.",
    code='invalid'
)

Tags: django字符串renumbermessagephone电话号码数字
1条回答
网友
1楼 · 发布于 2024-07-05 08:51:02

我觉得你真的做不到。。。但是,您可能只将表单输入指定为数字(可能使用forms.IntegerField

或者你可以自己写验证器

from django.core.exceptions import ValidationError

def validate_numeric(value):
    if not (9 <= len(re.sub("[^0-9]","",value)) <= 15):
        raise ValidationError('%s is not a valid phone number' % value)

相关问题 更多 >