Card number checksum (Luhn)

A free easy coding practice problem from security. Solve it in JavaScript, TypeScript or Python and check your solution against fresh hidden tests — edge cases and random inputs — as often as you like.

Difficulty
Easy
Type
Function
Topic
Security
Languages
JavaScript, TypeScript or Python

Problem

s is a card number as a customer typed it. Remove all spaces. Return true when what remains has at least 2 characters, consists only of digits 0–9, and passes the Luhn checksum; otherwise false (any other character, e.g. a dash or a letter, makes it invalid).

Luhn: starting from the RIGHTMOST digit, double every second digit (the 2nd, 4th, 6th, … counted from the right); if a doubled value is greater than 9, subtract 9. Sum all the digits (doubled or not). The number is valid when the sum is divisible by 10.

s has at most 40 characters.

Function signature

// JavaScript
function isValidCardNumber(s)

// TypeScript
function isValidCardNumber(s: any): any

// Python
def is_valid_card_number(s):

Examples

  1. isValidCardNumber("4539 1488 0343 6467") → true
  2. isValidCardNumber("79927398713") → true
  3. isValidCardNumber("1234 5678 9012") → false

How checking works

Run your code against the examples above, then submit a check: it runs on the server against hidden tests built fresh each time, including edge cases and random inputs. Practice is untimed and never affects a verified score; when you are ready, take a graded coding challenge to earn a badge.

More practice problems

Next steps