Login

"Ukrainian telephone number" model and form fields.

Author:
I159
Posted:
October 25, 2011
Language:
Python
Version:
1.2
Score:
0 (after 0 ratings)

Fields are validate Ukrainian phone numbers in popular formats.

 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'^(\+38)?\(?0\d{2}\)?[-\s]?\d{3}([-\s]\d{2}){2}$')


class UAPhoneNumberField(CharField):
    default_error_messages = {
        'invalid': _('Phone numbers must be in +38(0XX)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 11 months, 2 weeks ago
  2. JSONRequestMiddleware adds a .json() method to your HttpRequests by cdcarter 11 months, 3 weeks ago
  3. Serializer factory with Django Rest Framework by julio 1 year, 6 months ago
  4. Image compression before saving the new model / work with JPG, PNG by Schleidens 1 year, 7 months ago
  5. Help text hyperlinks by sa2812 1 year, 7 months ago

Comments

vosi (on October 25, 2011):

ваще не верный формат

код страны +380!

код региона мин 2 знака - макс 4

общая длина код региона + тел. номер 9 знаков

44 5556644 - киев (внутр формат) + не забываем 0

поэтому, международный формат +380 44 5556644

внутренний формат 044 5556644

#

g1smd (on September 6, 2012):

Error.

The country code for Ukraine is +380 and NOT +38.

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

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

#

Please login first before commenting.