Skip to content

Instantly share code, notes, and snippets.

@nabucosound
Created April 12, 2016 15:55
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save nabucosound/c22c0e7675818fc2eeba249fe6fb1339 to your computer and use it in GitHub Desktop.
Save nabucosound/c22c0e7675818fc2eeba249fe6fb1339 to your computer and use it in GitHub Desktop.
Django form field for the Mexican CLABE (Clave Bancaria Estandarizada)
import re
from django import forms
from django.core.exceptions import ValidationError
class CLABEField(forms.Field):
"""
Django form field for the mexican CLABE (Clave Bancaria Estandarizada,
Spanish for "standardized banking cipher"), a banking standard for the
numbering of bank accounts in Mexico.
More info: https://en.wikipedia.org/wiki/CLABE
"""
def to_python(self, value):
if not value:
return ''
return value
def validate(self, value):
"""
Validate that the input is a valid CLABE number, that is, the last
digit (the control digit or "digito de control") matches the formula
specified to calculate it.
"""
super(CLABEField, self).validate(value)
# Remove whitespace characters
orig_clabe = re.sub('\s+', '', value)
# Validate that value is 18 digit
if len(orig_clabe) != 18 or not orig_clabe.isdigit():
raise ValidationError('Please introduce a valid CLABE number')
# Get bank key, branch key and account number (first 17 digits)
digitos_banco = orig_clabe[:-1]
# Do the math
factores_peso = "37137137137137137"
productos = [(int(val[0]) * int(val[1])) % 10 for val in zip(digitos_banco, factores_peso)]
sum_productos = sum(productos)
mod_productos = sum_productos % 10
digito_control = (10 - mod_productos) % 10
# Confirm if our result digit is same as the one found in the last char
if digito_control == int(orig_clabe[-1]):
return True
else:
raise ValidationError('Please introduce a valid CLABE number')
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment