summaryrefslogtreecommitdiffstats
path: root/webapp/django/contrib/localflavor/pe/forms.py
blob: d83a2225bef54a4af87ec314551e47f2f8d10553 (plain)
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
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
# -*- coding: utf-8 -*-
"""
PE-specific Form helpers.
"""

from django.forms import ValidationError
from django.forms.fields import RegexField, CharField, Select, EMPTY_VALUES
from django.utils.translation import ugettext_lazy as _

class PERegionSelect(Select):
    """
    A Select widget that uses a list of Peruvian Regions as its choices.
    """
    def __init__(self, attrs=None):
        from pe_region import REGION_CHOICES
        super(PERegionSelect, self).__init__(attrs, choices=REGION_CHOICES)

class PEDNIField(CharField):
    """
    A field that validates `Documento Nacional de IdentidadŽ (DNI) numbers.
    """
    default_error_messages = {
        'invalid': _("This field requires only numbers."),
        'max_digits': _("This field requires 8 digits."),
    }

    def __init__(self, *args, **kwargs):
        super(PEDNIField, self).__init__(max_length=8, min_length=8, *args,
                **kwargs)

    def clean(self, value):
        """
        Value must be a string in the XXXXXXXX formats.
        """
        value = super(PEDNIField, self).clean(value)
        if value in EMPTY_VALUES:
            return u''
        if not value.isdigit():
            raise ValidationError(self.error_messages['invalid'])
        if len(value) != 8:
            raise ValidationError(self.error_messages['max_digits'])

        return value

class PERUCField(RegexField):
    """
    This field validates a RUC (Registro Unico de Contribuyentes). A RUC is of
    the form XXXXXXXXXXX.
    """
    default_error_messages = {
        'invalid': _("This field requires only numbers."),
        'max_digits': _("This field requires 11 digits."),
    }

    def __init__(self, *args, **kwargs):
        super(PERUCField, self).__init__(max_length=11, min_length=11, *args,
            **kwargs)

    def clean(self, value):
        """
        Value must be an 11-digit number.
        """
        value = super(PERUCField, self).clean(value)
        if value in EMPTY_VALUES:
            return u''
        if not value.isdigit():
            raise ValidationError(self.error_messages['invalid'])
        if len(value) != 11:
            raise ValidationError(self.error_messages['max_digits'])
        return value