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
- Serializer factory with Django Rest Framework by julio 3 months, 2 weeks ago
- Image compression before saving the new model / work with JPG, PNG by Schleidens 4 months ago
- Help text hyperlinks by sa2812 5 months ago
- Stuff by NixonDash 7 months, 1 week ago
- Add custom fields to the built-in Group model by jmoppel 9 months, 1 week ago
Comments
Please login first before commenting.