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