app/django/contrib/localflavor/pe/forms.py
changeset 54 03e267d67478
child 323 ff1a9aa48cfd
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/app/django/contrib/localflavor/pe/forms.py	Fri Jul 18 18:22:23 2008 +0000
@@ -0,0 +1,71 @@
+# -*- coding: utf-8 -*-
+"""
+PE-specific Form helpers.
+"""
+
+from django.newforms import ValidationError
+from django.newforms.fields import RegexField, CharField, Select, EMPTY_VALUES
+from django.utils.translation import ugettext
+
+class PEDepartmentSelect(Select):
+    """
+    A Select widget that uses a list of Peruvian Departments as its choices.
+    """
+    def __init__(self, attrs=None):
+        from pe_department import DEPARTMENT_CHOICES
+        super(PEDepartmentSelect, self).__init__(attrs, choices=DEPARTMENT_CHOICES)
+
+class PEDNIField(CharField):
+    """
+    A field that validates `Documento Nacional de IdentidadŽ (DNI) numbers.
+    """
+    default_error_messages = {
+        'invalid': ugettext("This field requires only numbers."),
+        'max_digits': ugettext("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': ugettext("This field requires only numbers."),
+        'max_digits': ugettext("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
+