|
1 """ |
|
2 JP-specific Form helpers |
|
3 """ |
|
4 |
|
5 from django.core import validators |
|
6 from django.newforms import ValidationError |
|
7 from django.utils.translation import ugettext |
|
8 from django.newforms.fields import RegexField, Select |
|
9 |
|
10 class JPPostalCodeField(RegexField): |
|
11 """ |
|
12 A form field that validates its input is a Japanese postcode. |
|
13 |
|
14 Accepts 7 digits, with or without a hyphen. |
|
15 """ |
|
16 default_error_messages = { |
|
17 'invalid': ugettext('Enter a postal code in the format XXXXXXX or XXX-XXXX.'), |
|
18 } |
|
19 |
|
20 def __init__(self, *args, **kwargs): |
|
21 super(JPPostalCodeField, self).__init__(r'^\d{3}-\d{4}$|^\d{7}$', |
|
22 max_length=None, min_length=None, *args, **kwargs) |
|
23 |
|
24 def clean(self, value): |
|
25 """ |
|
26 Validates the input and returns a string that contains only numbers. |
|
27 Returns an empty string for empty values. |
|
28 """ |
|
29 v = super(JPPostalCodeField, self).clean(value) |
|
30 return v.replace('-', '') |
|
31 |
|
32 class JPPrefectureSelect(Select): |
|
33 """ |
|
34 A Select widget that uses a list of Japanese prefectures as its choices. |
|
35 """ |
|
36 def __init__(self, attrs=None): |
|
37 from jp_prefectures import JP_PREFECTURES |
|
38 super(JPPrefectureSelect, self).__init__(attrs, choices=JP_PREFECTURES) |