Skip to content

Commit

Permalink
PhoneNumberField
Browse files Browse the repository at this point in the history
  • Loading branch information
gavinwahl committed Feb 13, 2013
1 parent 6e992ce commit 76302d0
Show file tree
Hide file tree
Showing 2 changed files with 32 additions and 4 deletions.
30 changes: 30 additions & 0 deletions fusionbox/forms/fields.py
Expand Up @@ -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
Expand Down Expand Up @@ -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 changes: 2 additions & 4 deletions setup.py
@@ -1,6 +1,4 @@
#!/usr/bin/env python
import os
import re
from setuptools import setup, find_packages

__doc__="""
Expand Down Expand Up @@ -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'],
)

0 comments on commit 76302d0

Please sign in to comment.