【问题标题】:python regex remove all non-numberic characters and ensure valid phone numberpython regex 删除所有非数字字符并确保有效的电话号码
【发布时间】:2015-10-03 19:09:55
【问题描述】:

我想将我所有的电话号码验证移到一个 django 验证器字段中。如何使用这个phone number 验证器来包括剥离字符串中的所有非数字字段?

例如'123.123.1234' 会变成 '1231231234'

我知道你可以用 replaceAll( "[^\\d]", "" ) 之类的替换来做到这一点,但它必须是 django 验证器的一个正则表达式

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

【问题讨论】:

    标签: python regex django


    【解决方案1】:

    我不认为你真的可以这样做......但是你可以将表单输入指定为仅数字(可能使用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)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2020-09-03
      • 1970-01-01
      • 2021-03-27
      • 1970-01-01
      • 2010-11-17
      • 1970-01-01
      • 2017-03-21
      相关资源
      最近更新 更多