Login

A RegexpField that clean the regex match using the desired format

Author:
nasp
Posted:
September 18, 2010
Language:
Python
Version:
1.2
Tags:
regex format field
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. Bitwise operator queryset filter by hgeerts@osso.nl 4 years, 11 months ago
  2. Url filter middleware by limodou 8 years, 1 month ago
  3. Dynamically change a form select widget to a hidden widget by epicserve 5 years, 9 months ago
  4. simple string formatting filter by gsf0 7 years, 7 months ago
  5. Replacing pattern groups by values by marinho 3 years, 7 months ago

Comments

Please login first before commenting.