Skip to content

HTTPS clone URL

Subversion checkout URL

You can clone with HTTPS or Subversion.

Download ZIP
Browse files

PhoneNumberField

  • Loading branch information...
commit 76302d0e94480f4d36d1691853ac8ca5ff047d2f 1 parent 6e992ce
Gavin Wahl gavinwahl authored
Showing with 32 additions and 4 deletions.
  1. +30 −0 fusionbox/forms/fields.py
  2. +2 −4 setup.py
30 fusionbox/forms/fields.py
View
@@ -9,6 +9,8 @@
import datetime
from functools import partial
+import phonenumbers
+
from django import forms
from django.contrib.auth.forms import ReadOnlyPasswordHashWidget
from django.utils.safestring import mark_safe
@@ -143,3 +145,31 @@ def render(self, name, value, attrs):
)
return mark_safe(hidden)
+
+
+class PhoneNumberField(forms.CharField):
+ """
+ A USA or international phone number field. Normalizes its value to a common
+ US format '(303) 555-5555' for US phone numbers, and an international
+ format for others - '+86 10 6944 5464'. Also supports extensions --
+ '3035555555ex12' -> '(303) 555-5555 ext. 12.'
+ """
+
+ default_error_messages = {
+ 'invalid': 'Enter a valid phone number.',
+ }
+
+ def clean(self, value):
+ if not value:
+ return value
+ try:
+ number = phonenumbers.parse(value, 'US')
+ except phonenumbers.NumberParseException:
+ raise forms.ValidationError(self.error_messages['invalid'])
+ if not phonenumbers.is_valid_number(number):
+ raise forms.ValidationError(self.error_messages['invalid'])
+
+ if number.country_code == 1:
+ return phonenumbers.format_number(number, phonenumbers.PhoneNumberFormat.NATIONAL)
+ else:
+ return phonenumbers.format_number(number, phonenumbers.PhoneNumberFormat.INTERNATIONAL)
6 setup.py
View
@@ -1,6 +1,4 @@
#!/usr/bin/env python
-import os
-import re
from setuptools import setup, find_packages
__doc__="""
@@ -31,7 +29,7 @@
'Environment :: Web Environment',
'Framework :: Django',
],
- install_requires = ['BeautifulSoup', 'PyYAML', 'markdown'],
- requires = ['BeautifulSoup', 'PyYAML', 'markdown'],
+ install_requires = ['BeautifulSoup', 'PyYAML', 'markdown', 'phonenumbers'],
+ requires = ['BeautifulSoup', 'PyYAML', 'markdown', 'phonenumbers'],
)
Please sign in to comment.
Something went wrong with that request. Please try again.