Python program to check credit card number is valid or not

Credit card numbers must follow specific formatting rules to be considered valid. We need to check if a credit card number meets all the required criteria including format, length, and digit patterns.

Credit Card Validation Rules

A valid credit card number must satisfy these conditions ?

  • Start with 4, 5, or 6

  • Be exactly 16 digits long

  • Contain only numeric digits

  • May have digits grouped in four sets separated by hyphens

  • Must not use spaces, underscores, or other separators

  • Must not have 4 or more consecutive identical digits

Implementation

Here's a complete solution to validate credit card numbers ?

import re

def is_valid_credit_card(card_number):
    # Check if card has hyphens
    if card_number.count("-") > 0:
        # Split by hyphens
        parts = card_number.split("-")
        
        # Must have exactly 4 groups
        if len(parts) != 4:
            return False
        
        # Each group must have exactly 4 digits
        for part in parts:
            if len(part) != 4 or not part.isdigit():
                return False
    else:
        # No hyphens - must be 16 digits
        if len(card_number) != 16 or not card_number.isdigit():
            return False
    
    # Remove hyphens for further validation
    clean_number = card_number.replace("-", "")
    
    # Check if starts with 4, 5, or 6 and is 16 digits
    if not re.match(r"^[456][0-9]{15}$", clean_number):
        return False
    
    # Check for 4+ consecutive same digits
    if re.search(r"([0-9])\1{3,}", clean_number):
        return False
    
    return True

# Test cases
test_cards = [
    "5423-2578-8632-6589",
    "4253625879615786", 
    "5555-5555-5555-5555",  # Invalid: 4+ consecutive same digits
    "51-67-89-45",          # Invalid: not 4 digits per group
    "4424444424442444"      # Invalid: 4+ consecutive same digits
]

for card in test_cards:
    result = is_valid_credit_card(card)
    print(f"Card: {card} -> Valid: {result}")
Card: 5423-2578-8632-6589 -> Valid: True
Card: 4253625879615786 -> Valid: True
Card: 5555-5555-5555-5555 -> Valid: False
Card: 51-67-89-45 -> Valid: False
Card: 4424444424442444 -> Valid: False

How the Validation Works

The validation process follows these steps ?

  1. Format Check: If hyphens are present, ensure exactly 4 groups of 4 digits each

  2. Length Check: Without hyphens, the number must be exactly 16 digits

  3. Starting Digit: Must begin with 4, 5, or 6

  4. Consecutive Digits: No 4 or more identical consecutive digits allowed

Key Regular Expressions

  • ^[456][0-9]{15}$ - Matches numbers starting with 4, 5, or 6 followed by 15 digits

  • ([0-9])\1{3,} - Detects 4 or more consecutive identical digits

Conclusion

This credit card validator checks format, length, starting digit, and consecutive digit patterns. Use regular expressions for pattern matching and string methods for format validation.

Updated on: 2026-03-26T15:45:32+05:30

4K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements