Skip to content

Instantly share code, notes, and snippets.

@jacoor
Created June 10, 2015 20:20
Show Gist options
  • Save jacoor/322d156f5691d60fa677 to your computer and use it in GitHub Desktop.
Save jacoor/322d156f5691d60fa677 to your computer and use it in GitHub Desktop.
Django rest framework uszipcode field
from rest_framework.fields import RegexField
from localflavor.us.forms import USZipCodeField as FormUSZipCodeField
class USZipCodeField(RegexField):
""""
A form field that validates input as a U.S. ZIP code. Valid formats are
XXXXX or XXXXX-XXXX.
.. note::
If you are looking for a form field with a list of U.S. Postal Service
locations please use :class:`~localflavor.us.forms.USPSSelect`.
.. versionadded:: 1.1
Whitespace around the ZIP code is accepted and automatically trimmed.
"""
type_name = 'USZipCodeField'
type_label = 'zipcode'
form_field_class = FormUSZipCodeField
default_error_messages = {
'invalid': _('Enter a zip code in the format XXXXX or XXXXX-XXXX.'),
}
def __init__(self, regex, max_length=None, min_length=None, *args, **kwargs):
super(USZipCodeField, self).__init__(r'^\d{5}(?:-\d{4})?$',
max_length, min_length, *args, **kwargs)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment