Login

"Ukrainian telephone number" model and form fields v2 UAPhoneNumberField (improved)

Author:
g1smd
Posted:
September 6, 2012
Language:
Python
Version:
1.4
Score:
1 (after 1 ratings)

Validate Ukraine telephone numbers in popular formats:

+380 XX XXX-XX-XX

    0XX-XXX-XX-XX

   (0XX) XXX-XX-XX

This snippet fixes the errors found in http://djangosnippets.org/snippets/2579/

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
# form field
import re

from django.forms.fields import CharField
from django.core.validators import EMPTY_VALUES
from django.forms import ValidationError
from django.utils.translation import ugettext_lazy as _

phone_digits = re.compile(r'^(\+380\s?|\(?0)\d{2}\)?[-\s]?\d{3}([-\s]\d{2}){2}$')


class UAPhoneNumberField(CharField):
default_error_messages = {
    'invalid': _('Phone numbers must be in +380 XX XXX-XX-XX,\
     0XX-XXX-XX-XX, or (0XX) XXX-XX-XX format.'),
    }

    def clean(self, value):
        super(UAPhoneNumberField, self).clean(value)
        if value in EMPTY_VALUES:
            return u''
        match = phone_digits.match(value)
        if match:
            return value
        raise ValidationError(self.error_messages['invalid'])

# model field
from django.db.models.fields import CharField
from django.utils.translation import ugettext_lazy as _

from helpers.form_fields import UAPhoneNumberField


class PhoneNumberField(CharField):

    description = _("Ukrainian phone number")

    def __init__(self, *args, **kwargs):
        kwargs['max_length'] = 17
        super(PhoneNumberField, self).__init__(*args, **kwargs)

    def formfield(self, **kwargs):
        defaults = {'form_class': UAPhoneNumberField}
        defaults.update(kwargs)
        return super(PhoneNumberField, self).formfield(**defaults)

More like this

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

Comments

Please login first before commenting.