Skip to content

Commit

Permalink
Add validate_phonenumber to allow short numbers
Browse files Browse the repository at this point in the history
  • Loading branch information
francoisfreitag committed Jun 14, 2024
1 parent b8d1886 commit b255326
Show file tree
Hide file tree
Showing 2 changed files with 33 additions and 0 deletions.
12 changes: 12 additions & 0 deletions phonenumber_field/validators.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import phonenumbers
from django.core.exceptions import ValidationError
from django.utils.translation import gettext_lazy as _

Expand All @@ -10,3 +11,14 @@ def validate_international_phonenumber(value):
raise ValidationError(
_("The phone number entered is not valid."), code="invalid"
)


def validate_phonenumber(value):
phone_number = to_python(value)
if isinstance(phone_number, PhoneNumber) and not (
phonenumbers.is_valid_number(phone_number)
or phonenumbers.is_valid_short_number(phone_number)
):
raise ValidationError(
_("The phone number entered is not valid."), code="invalid"
)
21 changes: 21 additions & 0 deletions tests/test_formfields.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@

from phonenumber_field.formfields import PhoneNumberField, SplitPhoneNumberField
from phonenumber_field.phonenumber import PhoneNumber
from phonenumber_field.validators import validate_phonenumber

ALGERIAN_PHONE_NUMBER = "+213799136332"

Expand Down Expand Up @@ -132,6 +133,16 @@ class PhoneNumberForm(forms.Form):
form.errors, {"number": ["Enter a valid phone number (e.g. +12125552368)."]}
)

def test_validate_shortcode(self):
class ShortCodePhoneNumberField(PhoneNumberField):
default_validators = [validate_phonenumber]

class TestForm(forms.Form):
phone = ShortCodePhoneNumberField(region="FR")

form = TestForm({"phone": "1010"})
self.assertIs(form.is_valid(), True)


class SplitPhoneNumberFormFieldTest(SimpleTestCase):
def example_number(self, region_code: str) -> PhoneNumber:
Expand Down Expand Up @@ -580,3 +591,13 @@ class TestForm(forms.Form):
form = TestForm(phone_data)
self.assertIs(form.is_valid(), False)
self.assertEqual(form.errors["phone"], [error_message])

def test_validate_shortcode(self):
class ShortCodeSplitPhoneNumberField(SplitPhoneNumberField):
default_validators = [validate_phonenumber]

class TestForm(forms.Form):
phone = ShortCodeSplitPhoneNumberField()

form = TestForm({"phone_0": "FR", "phone_1": "1010"})
self.assertIs(form.is_valid(), True)

0 comments on commit b255326

Please sign in to comment.