Login

"Ukrainian telephone number" model and form fields.

Author:
I159
Posted:
October 25, 2011
Language:
Python
Version:
1.2
Tags:
form_field model_field
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. "Ukrainian telephone number" model and form fields v2 UAPhoneNumberField (improved) by g1smd 2 years, 8 months ago
  2. Type checking templatetag filters by marcorogers 5 years, 3 months ago
  3. BigIntegerField and BigAutoField by fnl 6 years, 5 months ago
  4. Generic CSV Export by zbyte64 6 years, 11 months ago
  5. Convert Microsoft "smart quotes" to standard quotes by nomadjourney 4 years, 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.