Login

A RegexpField that clean the regex match using the desired format

Author:
nasp
Posted:
September 18, 2010
Language:
Python
Version:
1.2
Score:
1 (after 1 ratings)

I wanted a way to allow flexible phone number validation while making sure the saved data was uniform.

ex.

With: RegexFormatField(r'^(?(?P<area>d{3}))?[-s.]?(?P<local>d{3})[-s.]?(?P<subscriber>d{4})$', format='%(area)s %(local)s-%(subscriber)s')

input: (444) 444-4444 444 444-4444 444-444-4444 444.444.4444 4444444444

output: 444 444-4444

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
from django.forms import RegexField

class RegexFormatField(RegexField):
     
    def __init__(self, *args, **kwargs):
        if 'format' in kwargs:
            self.format = kwargs['format']
            del kwargs['format']
        super(RegexFormatField, self).__init__(*args, **kwargs)
        
    def clean(self, value):
        value = super(RegexFormatField, self).clean(value)
        if self.format is not None:
            value = self.format % self.regex.match(value).groupdict()
        return value

More like this

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

Comments

Please login first before commenting.