Ticket #11217: localflavor.hu.diff

File localflavor.hu.diff, 7.2 KB (added by nagyv, 6 years ago)

Hungarian localflavor patch

  • django/contrib/localflavor/ro/forms.py

     
    88from django.forms import ValidationError, Field, RegexField, Select
    99from django.forms.fields import EMPTY_VALUES
    1010from django.utils.translation import ugettext_lazy as _
     11from django.contrib.localflavor.generic.util import validate_iban
    1112
    1213class ROCIFField(RegexField):
    1314    """
     
    150151        Strips - and spaces, performs country code and checksum validation
    151152        """
    152153        value = super(ROIBANField, self).clean(value)
    153         value = value.replace('-','')
    154         value = value.replace(' ','')
    155         value = value.upper()
    156         if value[0:2] != 'RO':
     154        if validate_iban(value, 20):
     155            return value
     156        else:
    157157            raise ValidationError(self.error_messages['invalid'])
    158         numeric_format = ''
    159         for char in value[4:] + value[0:4]:
    160             if char.isalpha():
    161                 numeric_format += str(ord(char) - 55)
    162             else:
    163                 numeric_format += char
    164         if int(numeric_format) % 97 != 1:
    165             raise ValidationError(self.error_messages['invalid'])
    166         return value
    167158
    168159class ROPhoneNumberField(RegexField):
    169160    """Romanian phone number field"""
  • django/contrib/localflavor/generic/util.py

     
     1def validate_iban(value, length):
     2    '''
     3    Validate an International Bank Account Number (IBAN)
     4   
     5    Based on
     6    * http://en.wikipedia.org/wiki/International_Bank_Account_Number#Calculating_and_validating_IBAN_checksums
     7    * and django.contrib.localflavor.ro.ROIBANField
     8   
     9    @param value: the value to check
     10    @param length: the length of the BBAN specific to each country
     11    '''
     12    value = value.replace('-', '')
     13    value = value.replace('', '')
     14    if not len(value) == length:
     15        return False
     16   
     17    value = value.upper()
     18    for char in value[4:] + value[0:4]:
     19        if char.isalpha():
     20            numeric_format += str(ord(char) - 55)
     21        else:
     22            numeric_format += char
     23    if int(numeric_format) % 97 != 1:
     24        return False
     25    return value
     26 No newline at end of file
  • django/contrib/localflavor/hu/forms.py

     
     1# -*- coding: utf-8 -*
     2"""
     3IT-specific Form helpers
     4"""
     5
     6from django.forms import ValidationError
     7from django.forms.fields import Field, RegexField, Select, EMPTY_VALUES
     8from django.utils.translation import ugettext_lazy as _
     9from django.utils.encoding import smart_unicode
     10from django.contrib.localflavor.generic.util import validate_iban
     11import re
     12
     13class HUZipCodeField(RegexField):
     14    default_error_messages = {
     15        'invalid': _('Enter a valid zip code.'),
     16    }
     17    def __init__(self, *args, **kwargs):
     18        super(HUZipCodeField, self).__init__(r'^\d{4}$',
     19        max_length=None, min_length=None, *args, **kwargs)
     20
     21class HUVatNumberField(Field):
     22    """
     23    A form field that validates Hungarian VAT numbers (adószám).
     24    """
     25    default_error_messages = {
     26        'invalid': _(u'Enter a valid VAT number.'),
     27    }
     28
     29    def clean(self, value):
     30        value = super(HUVatNumberField, self).clean(value)
     31        if value == u'':
     32            return value
     33        try:
     34            vat_number = int(value)
     35        except ValueError:
     36            raise ValidationError(self.error_messages['invalid'])
     37       
     38        if not len(vat_number) == 11:
     39            raise ValidationError(self.error_messages['invalid'])
     40        elif not vat_number[9] in (1,2,3):
     41            raise ValidationError(self.error_messages['invalid'])
     42        return smart_unicode(vat_number)
     43   
     44class HUIBANField(RegexField):
     45    '''
     46    A form field that validates Hungarian IBAN codes
     47   
     48    Format: HUkk BBBB BBBC CCCC CCCC CCCC CCCC
     49        B = bank code, C = account No.
     50    '''
     51    default_error_messages = {
     52          'invalid': _('Enter a valid IBAN number in the format HUkk XXXX XXXX XXXX XXXX XXXX XXXX'),
     53      }
     54    def __init__(self, *args, **kwargs):
     55        super(HUIBANField, self).__init__(r'^HU[0-9-\s]{26,30}$',
     56            max_length=32, min_length=28, *args, **kwargs)
     57
     58    def clean(self, value):
     59        '''
     60        Strips unnecessary values, and perform checksum validation
     61        '''
     62        value = super(HUIBANField, self).clean(value)
     63        if validate_iban(value, 24):
     64            return value
     65        else:
     66            raise ValidationError(self.error_messages['invalid'])
     67
     68class HUPhoneNumberField(RegexField):
     69    '''
     70    A form field to represent Hungarian phone numbers
     71    '''
     72    default_error_messages = {
     73      'invalid': _('Enter a valid phone number. E.g. 1/234-5678')
     74      }
     75    def __init__(self, *args, **kwargs):
     76        super(HUPhoneNumberField, self).__init__(r'^\d{8,15}$',
     77             max_length=16, min_length=7, *args, **kwargs)
     78       
     79    def clean(self, value):
     80        '''
     81        Strip 06, whitespaces, dashes
     82        '''
     83        value = super(HUPhoneNumberField, self).clean(value)
     84        value = value.replace(' ', '')
     85        value = value.replace('-', '')
     86        value = value.replace('/', '')
     87        value = value[:2] == '06' and value[2:] or value
     88        # mobile phone numbers might have 8 digits
     89        if not len(value) == 8: # Bp: 1+7, other: 2+6
     90            raise ValidationError(self.error_messages['invalid'])
     91        elif len(value) == 10 and value[:2] not in (20, 30, 70, 71):
     92            raise ValidationError(self.error_messages['invalid'])
     93        return value
  • docs/ref/contrib/localflavor.txt

     
    4848    * Finland_
    4949    * France_
    5050    * Germany_
     51    * Hungary_
    5152    * Iceland_
    5253    * India_
    5354    * Italy_
     
    8889.. _Finland: `Finland (fi)`_
    8990.. _France: `France (fr)`_
    9091.. _Germany: `Germany (de)`_
     92.. _Hungary: `Hungary (hu`_
    9193.. _The Netherlands: `The Netherlands (nl)`_
    9294.. _Iceland: `Iceland (is\_)`_
    9395.. _India: `India (in\_)`_
     
    308310.. class:: de.forms.DEStateSelect
    309311
    310312    A ``Select`` widget that uses a list of German states as its choices.
     313   
     314Hungary (``hu``)
     315================
    311316
     317.. class:: hu.forms.HUZipCodeField
     318
     319        A form field to check Hungarian ZIP codes. They should be 4 digits long.
     320       
     321.. class:: hu.forms.HUVatNumberField
     322
     323        A form field to check Hungarian VAT numbers (adószám).
     324       
     325.. class:: hu.forms.HUIBANField
     326
     327        A form field to check Hungarian IBAN numbers.
     328       
     329.. class:: hu.forms.HUPhoneNumberField
     330
     331        A form field to check Hungarian phone numbers.
     332
    312333The Netherlands (``nl``)
    313334========================
    314335
Back to Top