Skip to content

Instantly share code, notes, and snippets.

@zokis
Last active December 16, 2015 14:19
Show Gist options
  • Save zokis/5447451 to your computer and use it in GitHub Desktop.
Save zokis/5447451 to your computer and use it in GitHub Desktop.
BR TelefoneField for Django model TelefoneField + Widget
from django.forms.widgets import TextInput
from django.contrib.db import models
import re
class TelefoneWidget(TextInput):
def __init__(self, attrs=None):
attrs_default = {'placeholder': 'xx-(x)xxxx-xxxx', 'maxlength': 13}
if attrs:
attrs_default.update(attrs)
super(TelefoneWidget, self).__init__(attrs=attrs_default)
class TelefoneField(models.CharField):
def formfield(self, *args, **kwargs):
kwargs['widget'] = TelefoneWidget()
return super(TelefoneField, self).formfield(*args, **kwargs)
def clean(self, value, model_instance):
value = value.replace(' ', '')
regex = re.compile(r'^([0-9]{2})-(([0-9]{5})|([0-9]{4}))-([0-9]{4})$', re.IGNORECASE | re.UNICODE)
if len(regex.findall(value)) != 1:
raise ValidationError(u'Telefone %s inválido' % value)
return super(TelefoneField, self).clean(value, model_instance)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment