Validating Credit Card Numbers

  • + 0 comments
    import re
    # Function to validate credit card numbers
    def validate_credit_card(card_number):	
        pattern = r'^[456]\d{3}(-?\d{4}){3}$'    # Regex pattern for a valid card number
    # Check if the card matches the pattern and has no consecutive repeated digits
        if re.match(pattern, card_number) and not re.search(r'(\d)\1{3,}', card_number.replace('-', '')):
            return "Valid"
        else:
            return "Invalid"
    no_of_cards = int(input())
    card_numbers = [input() for _ in range(no_of_cards)]
    
    # Applying the function to each card number
    results = [validate_credit_card(card) for card in card_numbers]
    for result in results:
        print(result)