def clean(self, value):
        super().clean(value)

        if value in self.empty_values:
            return self.empty_value

        # strip spaces and dashes
        value = value.replace(' ', '').replace('-', '')

        match = re.match(id_re, value)

        if not match:
            raise ValidationError(self.error_messages['invalid'])

        g = match.groupdict()

        try:
            # The year 2000 is conveniently a leapyear.
            # This algorithm will break in xx00 years which aren't leap years
            # There is no way to guess the century of a ZA ID number
            date(int(g['yy']) + 2000, int(g['mm']), int(g['dd']))
        except ValueError:
            raise ValidationError(self.error_messages['invalid'])

        if not luhn.is_valid(value):
            raise ValidationError(self.error_messages['invalid'])

        return value
Beispiel #2
0
    def clean(self, value):
        super().clean(value)

        if value in self.empty_values:
            return self.empty_value

        # strip spaces and dashes
        value = value.strip().replace(' ', '').replace('-', '')

        match = re.match(id_re, value)

        if not match:
            raise ValidationError(self.error_messages['invalid'])

        g = match.groupdict()

        try:
            # The year 2000 is conveniently a leapyear.
            # This algorithm will break in xx00 years which aren't leap years
            # There is no way to guess the century of a ZA ID number
            date(int(g['yy']) + 2000, int(g['mm']), int(g['dd']))
        except ValueError:
            raise ValidationError(self.error_messages['invalid'])

        if not luhn.is_valid(value):
            raise ValidationError(self.error_messages['invalid'])

        return value
Beispiel #3
0
def getBankNumbers(file):
    from stdnum import luhn
    banknums = []
    f = open(file, encoding='utf-8')  # 返回一个文件对象
    line = f.readline()  # 调用文件的 readline()方法
    while line:
        if line:
            try:
                banknum = {}
                arr = line.strip().split(',')
                # 邮储银行,1000000,绿卡银联标准卡,19,6,622188,1
                banknum['prefix'] = arr[5]
                banknum['bankName'] = BankSimplefy.simplefyBankName(arr[0])
                banknum['length'] = arr[3]
                # print(f'{banknum}')
                num_generator = cardNum_generator(banknum['prefix'],
                                                  int(banknum['length']))
                banknum['bankNumber'] = num_generator
                valid = luhn.is_valid(num_generator)
                # banknum['luhn_valid'] = valid
                # 校验luhn算法
                # print(f'校验luhn算法是否成功:{valid}')
                banknums.append(banknum)
            except Exception as e:
                LogUtil.info(f"{e}")
        line = f.readline()

    f.close()
    return banknums
Beispiel #4
0
def generateBankNumbers(file):
    from stdnum import luhn
    banknums = []
    f = open(file)  # 返回一个文件对象
    line = f.readline()  # 调用文件的 readline()方法
    while line:
        if line:
            try:
                banknum = {}
                arr = line.strip().split(',')
                pattern = re.compile("(\d*)开头的银行卡类型是(.*)")
                res = pattern.search(arr[0]).groups()
                banknum['prefix'] = res[0]
                banknum['bankName'] = BankSimplefy.simplefyBankName(res[1])
                pattern = re.compile("银行卡号数字长度为(\d*)位")
                res = pattern.search(arr[1]).groups()
                banknum['length'] = res[0]
                # print(f'{banknum}')
                num_generator = cardNum_generator(banknum['prefix'],
                                                  int(banknum['length']))
                banknum['bankNumber'] = num_generator
                valid = luhn.is_valid(num_generator)
                # banknum['luhn_valid'] = valid
                # 校验luhn算法
                # print(f'校验luhn算法是否成功:{valid}')
                banknums.append(banknum)
            except Exception as e:
                LogUtil.info(f"{e}")
        line = f.readline()

    f.close()
    return banknums
Beispiel #5
0
def is_validCC(number):
	"""
	Check if is a valid CC number
	:param number: number as string
	:return: True or False
	"""
	types = []
	types.append(["Mastercard", [51,52,53,54,55], 16, 19])
	types.append(["Visa", [4], 13, 16])
	types.append(["American Express", [34, 37], 15, 15])
	types.append(["Discover", [6011, range(622126, 622925), range(644,649), 65], 16, 16])
	types.append(["Diners Club - Carte Blanche", [300, 301, 302, 303, 304, 305], 14, 14])
	types.append(["Diners Club - International", [36], 14, 14])
	types.append(["Diners Club - USA & Canada", [54], 16, 16])
	types.append(["InstaPayment", [637, 638, 639], 16, 16])
	types.append(["JCB", [range(3528,3589)], 16, 16])
	types.append(["Laser", [6304, 6706, 6771, 6709], 16, 19])
	types.append(["Maestro", [5018, 5020, 5038, 5893, 6304, 6759, 6761, 6762, 6763], 16, 19])
	types.append(["Visa Electron", [4026, 417500, 4508, 4844, 4913, 4917], 16, 16])

	if len(number) < 12:
		return False

	luhn_check = luhn.is_valid(number)
	if not luhn_check:
		return False

	for vend in types:
		for pre in vend[1]:
			if number.startswith(str(pre)) and vend[3] <= len(number) <= vend[4]:
				return True
Beispiel #6
0
def luhn(candidate):
    """
    Checks a candidate number for validity according to the Luhn algorithm.

    Luhn algorithm is used in validation of, for example, credit cards.
    Both numeric and string candidates are accepted.

    .. deprecated:: 2.2
       Use the luhn function in the python-stdnum_ library instead.

    .. _python-stdnum: https://arthurdejong.org/python-stdnum/
    """
    warnings.warn(
        'luhn is deprecated in favor of the luhn function in the python-stdnum library.',
        RemovedInLocalflavor30Warning,
    )

    if not isinstance(candidate, str):
        candidate = str(candidate)

    # Our version returned True for empty strings.
    if candidate == '':
        return True

    return stdnum_luhn.is_valid(candidate)
    def clean(self, value):
        super().clean(value)
        if value in self.empty_values:
            return self.empty_value

        value = value.replace(' ', '').replace('-', '')
        if not self.r_valid.match(value) or not luhn.is_valid(value):
            raise ValidationError(self.error_messages['invalid'])
        return value
Beispiel #8
0
    def clean(self, value):
        super().clean(value)
        if value in self.empty_values:
            return self.empty_value

        value = value.replace(' ', '').replace('-', '')
        if not self.r_valid.match(value) or not luhn.is_valid(value):
            raise ValidationError(self.error_messages['invalid'])
        return value
Beispiel #9
0
    def clean(self, value):
        value = super().clean(value)
        if value in self.empty_values:
            return value

        value = value.replace(' ', '').replace('-', '')

        if not luhn.is_valid(value[:9]):
            raise ValidationError(self.error_messages['invalid'], code='invalid')
        return value
Beispiel #10
0
def get_bankcard_number():
    """获取真是银行卡号"""

    r_dir = config.__path__[0]
    f1 = os.path.join(r_dir, 'bankNum')
    with open(f1, 'r', encoding='utf-8') as f:
        temp = yaml.load(f)
        while True:
            res = random.choice(temp['Number'])
            # 判断银行卡号是否有效
            if luhn.is_valid(res):
                break
    return res
Beispiel #11
0
def valid(card):

    if not luhn.is_valid(card):
        return False

    key = BANKBIN.get(card[:7]) if BANKBIN.get(card[:7]) else BANKBIN.get(
        card[:6], None)

    if key:
        key = key.split('|')
        return {'bank': key[0], 'type': key[1]}

    return {'bank': u'未知银行卡', 'type': key[1]}
Beispiel #12
0
    def clean(self, value):
        value = super().clean(value)

        if value in EMPTY_VALUES:
            return ''

        match = id_number_re.match(value)
        if not match:
            raise ValidationError(self.error_messages['invalid'])

        value = match.group('number') + match.group('check')
        if not luhn.is_valid(value):
            raise ValidationError(self.error_messages['invalid'])
        return value
Beispiel #13
0
    def clean(self, value):
        value = super().clean(value)

        if value in self.empty_values:
            return value

        match = id_number_re.match(value)
        if not match:
            raise ValidationError(self.error_messages['invalid'], code='invalid')

        value = match.group('number') + match.group('check')
        if not luhn.is_valid(value):
            raise ValidationError(self.error_messages['invalid'], code='invalid')
        return value
Beispiel #14
0
    def clean(self, value):
        value = super(ILIDNumberField, self).clean(value)

        if value in EMPTY_VALUES:
            return ''

        match = id_number_re.match(value)
        if not match:
            raise ValidationError(self.error_messages['invalid'])

        value = match.group('number') + match.group('check')
        if not luhn.is_valid(value):
            raise ValidationError(self.error_messages['invalid'])
        return value
Beispiel #15
0
    def match_bankId(self, content):
        '''
        Bank Card Number Matching

        :param content:
        :return:
        '''
        bankIdsArr = []
        bankIds = re.findall(r"\d{19}|\d{15}", content)
        for bankId in bankIds:
            stat = luhn.is_valid(bankId)
            if stat == True:
                bankIdsArr.append(bankId)
        return bankIdsArr
Beispiel #16
0
    def clean(self, value):
        value = super().clean(value)
        if value in EMPTY_VALUES:
            return ''

        match = re.match(sin_re, value)
        if not match:
            raise ValidationError(self.error_messages['invalid'])

        number = '%s-%s-%s' % (match.group(1), match.group(2), match.group(3))
        check_number = '%s%s%s' % (match.group(1), match.group(2),
                                   match.group(3))
        if not luhn.is_valid(check_number):
            raise ValidationError(self.error_messages['invalid'])
        return number
Beispiel #17
0
def addbank(request):
    if request.method == 'POST':
        user = request.user
        bank = request.POST.get("bank", "")
        bankid = request.POST.get("bankid", "")
        status = request.POST.get("status", "")
        if bank and bankid:
            if luhn.is_valid(bankid):
                Bank.objects.create(user=user, bank=bank, bankid=bankid, status=status)
                return HttpResponse(json.dumps({"result": True, "data": "绑定成功", "error": ""}))
            else:
                return HttpResponse(json.dumps({"result": False, "data": "", "error": "无效卡号"}))
        else:
            return HttpResponse(json.dumps({"result":False, "data":"", "error":"输入项不能为空"}))
    if request.method == 'GET':
        return HttpResponse(json.dumps({"result": True, "data": "", "error": ""}))
Beispiel #18
0
    def clean(self, value):
        value = super().clean(value)
        if value in self.empty_values:
            return value

        match = re.match(sin_re, value)
        if not match:
            raise ValidationError(self.error_messages['invalid'],
                                  code='invalid')

        number = '%s-%s-%s' % (match.group(1), match.group(2), match.group(3))
        check_number = '%s%s%s' % (match.group(1), match.group(2),
                                   match.group(3))
        if not luhn.is_valid(check_number):
            raise ValidationError(self.error_messages['invalid'],
                                  code='invalid')
        return number
Beispiel #19
0
    def clean(self, value):
        super().clean(value)
        if value in self.empty_values:
            return self.empty_value
        val = re.sub('[\-\s]', '', force_text(value))
        if not val or len(val) < 11:
            raise ValidationError(self.error_messages['invalid'])
        if self.allow_test_value and val == '00000000000':
            return val
        if not all(char.isdigit() for char in val):
            raise ValidationError(self.error_messages['invalid'])

        self.check_date(val)
        if not luhn.is_valid(val):
            raise ValidationError(self.error_messages['invalid'])

        return val
Beispiel #20
0
    def clean(self, value):
        super().clean(value)
        if value in EMPTY_VALUES:
            return ''

        match = re.match(sin_re, value)
        if not match:
            raise ValidationError(self.error_messages['invalid'])

        number = '%s-%s-%s' % (match.group(1), match.group(2), match.group(3))
        check_number = '%s%s%s' % (
            match.group(1),
            match.group(2),
            match.group(3))
        if not luhn.is_valid(check_number):
            raise ValidationError(self.error_messages['invalid'])
        return number
Beispiel #21
0
    def clean(self, value):
        super().clean(value)
        if value in self.empty_values:
            return self.empty_value
        val = re.sub('[\-\s]', '', force_str(value))
        if not val or len(val) < 11:
            raise ValidationError(self.error_messages['invalid'])
        if self.allow_test_value and val == '00000000000':
            return val
        if not all(char.isdigit() for char in val):
            raise ValidationError(self.error_messages['invalid'])

        self.check_date(val)
        if not luhn.is_valid(val):
            raise ValidationError(self.error_messages['invalid'])

        return val
Beispiel #22
0
    def clean(self, value):
        super().clean(value)
        if value in EMPTY_VALUES:
            return ''

        value = re.sub(r'[\-\s]', '', value.strip())

        matches = jmbag_re.search(value)
        if matches is None:
            raise ValidationError(self.error_messages['invalid'])

        # Make sure the issue number is not zero.
        if matches.group('copy') == '0':
            raise ValidationError(self.error_messages['copy'])

        # Validate checksum using Luhn algorithm.
        if not luhn.is_valid(value):
            raise ValidationError(self.error_messages['invalid'])

        return '%s' % value
Beispiel #23
0
    def clean(self, value):
        super().clean(value)
        if value in EMPTY_VALUES:
            return ''

        value = re.sub(r'[\-\s]', '', value.strip())

        matches = jmbag_re.search(value)
        if matches is None:
            raise ValidationError(self.error_messages['invalid'])

        # Make sure the issue number is not zero.
        if matches.group('copy') == '0':
            raise ValidationError(self.error_messages['copy'])

        # Validate checksum using Luhn algorithm.
        if not luhn.is_valid(value):
            raise ValidationError(self.error_messages['invalid'])

        return '%s' % value
Beispiel #24
0
    def clean(self, value):
        value = super().clean(value)
        if value in self.empty_values:
            return value

        value = re.sub(r'[\-\s]', '', value)

        matches = jmbag_re.search(value)
        if matches is None:
            raise ValidationError(self.error_messages['invalid'], code='invalid')

        # Make sure the issue number is not zero.
        if matches.group('copy') == '0':
            raise ValidationError(self.error_messages['copy'], code='copy')

        # Validate checksum using Luhn algorithm.
        if not luhn.is_valid(value):
            raise ValidationError(self.error_messages['invalid'], code='invalid')

        return '%s' % value
Beispiel #25
0
def is_validCC(number):
    """
	Check if is a valid CC number
	:param number: number as string
	:return: True or False
	"""
    types = []
    types.append(["Mastercard", [51, 52, 53, 54, 55], 16, 19])
    types.append(["Visa", [4], 13, 16])
    types.append(["American Express", [34, 37], 15, 15])
    types.append([
        "Discover", [6011, range(622126, 622925),
                     range(644, 649), 65], 16, 16
    ])
    types.append([
        "Diners Club - Carte Blanche", [300, 301, 302, 303, 304, 305], 14, 14
    ])
    types.append(["Diners Club - International", [36], 14, 14])
    types.append(["Diners Club - USA & Canada", [54], 16, 16])
    types.append(["InstaPayment", [637, 638, 639], 16, 16])
    types.append(["JCB", [range(3528, 3589)], 16, 16])
    types.append(["Laser", [6304, 6706, 6771, 6709], 16, 19])
    types.append([
        "Maestro", [5018, 5020, 5038, 5893, 6304, 6759, 6761, 6762, 6763], 16,
        19
    ])
    types.append(
        ["Visa Electron", [4026, 417500, 4508, 4844, 4913, 4917], 16, 16])

    if len(number) < 12:
        return False

    luhn_check = luhn.is_valid(number)
    if not luhn_check:
        return False

    for vend in types:
        for pre in vend[1]:
            if number.startswith(
                    str(pre)) and vend[3] <= len(number) <= vend[4]:
                return True
Beispiel #26
0


from stdnum import luhn

print(luhn.is_valid("6222031001010038011"))
Beispiel #27
0
 def validate(self, ent):
     try:
         return (12 < len(ent) < 20) and is_valid(ent)
     except:
         return False
Beispiel #28
0
    def luhn_valid(cls, val):

        return luhn.is_valid(val)