Login

Smarter USPhoneNumberField

Author:
clamothe
Posted:
August 9, 2008
Language:
Python
Version:
.96
Score:
1 (after 1 ratings)

The original USPhoneNumberField only validates xxx-xxx-xxxx values.

This field validates...

(xxx) xxx xxxx xxx-xxx-xxxx (xxx)-xxx-xxxx many others.

Explanation of the regular expression:

  1. Accepts either (xxx) or xxx at the start of the value.
  2. Allows for any amount of dashes and spaces (including none) before the next set of digits.
  3. Accepts 3 digits
  4. Allows for any amount of dashes and spaces (including none) before the next set of digits.
  5. Accepts 4 digits, finishing the value.

This field saves in the same format that the original USPhoneNumberField does (xxx-xxx-xxxx).

Enjoy!

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
# stdlib
import re

# django
from django.forms.fields import EMPTY_VALUES, Field
from django.forms import ValidationError
from django.utils.encoding import smart_unicode


__all__ = ('phone_digits_re', 'USPhoneNumberField')
phone_digits_re = re.compile(r'^((\((?P<areacode_1>\d{3})\))|(?P<areacode_2>\d{3}))[ \-]*(?P<first>\d{3})[ \-]*(?P<last>\d{4})$')

class USPhoneNumberField(Field):
    " A USPhoneNumberField that accepts a wide variety of valid phone number patterns. "
    default_error_messages = {
        'invalid': u'The phone number is invalid.',
    }

    def clean(self, value):
        super(USPhoneNumberField, self).clean(value)
        if value in EMPTY_VALUES:
            return u''
        
        m = phone_digits_re.match( smart_unicode(value) )
        if m:
            return u'%s-%s-%s' % (m.group('areacode_1') or m.group('areacode_2'), m.group('first'), m.group('last'))
        raise ValidationError(self.error_messages['invalid'])

More like this

  1. Template tag - list punctuation for a list of items by shapiromatron 2 months, 2 weeks ago
  2. JSONRequestMiddleware adds a .json() method to your HttpRequests by cdcarter 2 months, 3 weeks ago
  3. Serializer factory with Django Rest Framework by julio 9 months, 2 weeks ago
  4. Image compression before saving the new model / work with JPG, PNG by Schleidens 10 months, 1 week ago
  5. Help text hyperlinks by sa2812 11 months ago

Comments

middlelord (on September 21, 2011):

Hello I am trying to implement but where do I place this code? in the Models.py or views.py ? Thank you for the Code

#

badrihippo (on May 18, 2015):

It's a form-field, not a model field (it inherits from django.forms.fields). So the best place would be forms.py of you're only using it in one form, or a new fields.py if you're going to use it in multiple places.

#

Please login first before commenting.