Created
June 10, 2015 21:12
-
-
Save jacoor/4a36712d134147bf81c6 to your computer and use it in GitHub Desktop.
django rest framework us phone field
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import re | |
from django.core.validators import EMPTY_VALUES | |
from django.utils.encoding import smart_text | |
from rest_framework.fields import CharField | |
from localflavor.us.forms import USPhoneNumberField as FormUSPhoneNumberField, phone_digits_re | |
from django.core.exceptions import ValidationError | |
class USPhoneNumberField(CharField): | |
""" | |
A form field that validates input as a U.S. phone number. | |
""" | |
default_error_messages = { | |
'invalid': _('Phone numbers must be in XXX-XXX-XXXX format.'), | |
} | |
type_name = 'USPhoneNumberField' | |
type_label = 'phone' | |
form_field_class = FormUSPhoneNumberField | |
def validate(self, value): | |
super(USPhoneNumberField, self).validate(value) | |
if value in EMPTY_VALUES: | |
return '' | |
value = re.sub('(\(|\)|\s+)', '', smart_text(value)) | |
m = phone_digits_re.search(value) | |
if m: | |
return '%s-%s-%s' % (m.group(1), m.group(2), m.group(3)) | |
raise ValidationError(self.error_messages['invalid']) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment