0

I'd like to move all of my phone number validation into one django validator field. How can I use this phone number validator to include stripping all non numeric fields in the string?

e.g. '123.123.1234' would become '1231231234'

I know you can do it with a replace such as replaceAll( "[^\\d]", "" ) but it needs to be one regex for the django validator

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'
)
Community
  • 1
  • 1
user2954587
  • 4,661
  • 6
  • 43
  • 101

1 Answers1

1

I dont think you can do that really ... however you could probably specify the form input as only numeric (perhaps with forms.IntegerField)

or you could write your own validator

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)
Joran Beasley
  • 110,522
  • 12
  • 160
  • 179