Login

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

Author:
g1smd
Posted:
September 6, 2012
Language:
Python
Version:
1.4
Tags:
field telephone area-code localflavor form_field UA form model_field
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. "Ukrainian telephone number" model and form fields. by I159 3 years, 6 months ago
  2. UKPhoneNumberField GB v2 by g1smd 2 years, 7 months ago
  3. UKPhoneNumberField GB v3 (improved) by g1smd 2 years, 7 months ago
  4. UKPhoneNumberField by nathan-reynolds 6 years, 5 months ago
  5. Convert Microsoft "smart quotes" to standard quotes by nomadjourney 4 years, 6 months ago

Comments

Please login first before commenting.