you type a card number into a form and it goes red before you even hit submit. no server call, nothing. that is the luhn check, and it is a much smaller thing than people think, so here is what it actually does.
start from the rightmost digit, that one is the check digit, leave it alone. moving left double every second digit. if a doubled digit is above 9 take 9 off it. add everything up. if the total ends in 0 the number passes. that is it. take 4242 4242 4242 4242, eight 8s and eight 2s, 64 plus 16 is 80, ends in 0, passes. take 79927398713, the doubled 9 becomes 18 then 9, the doubled 8 becomes 16 then 7, total 70, passes.
what it catches is one mistyped digit, or two neighbouring digits swapped. 4242 4242 4242 4241 fails, with those first 15 digits the last one has to be 2. swap two digits somewhere in the middle and it fails too. that is the job luhn was made for, typos, nothing else.
now the part people get wrong. passing does not mean the card exists. exactly one of the ten possible last digits fits, so a random 16 digit number passes about one time in ten. it does not mean the card is active or has money, only the bank that issued it knows that. and it does not mean it is safe to use in a test. random digits behind a real prefix can be somebody's live card, make sure of this okay. for testing a checkout use only what the gateway publishes, 4242 4242 4242 4242 for stripe test mode and 6527 6589 0000 1005 for the razorpay rupay test card. those work in test mode and nowhere else.
the first digits also name the scheme, 4 is visa, 51 to 55 or 2221 to 2720 is mastercard, 34 or 37 is amex, and a visa looking number with 15 digits gets flagged even if the luhn digit fits. 65 is listed for both discover and rupay and only the issuer knows which one.
i wrote all this up as a guide and the checker shows the whole table for any number you type, runs in your browser, nothing is uploaded, so ya i'm biased. guide is here https://theomnikit.com/guides/check-whether-a-card-number-is-valid?utm_source=devto&utm_medium=post&utm_campaign=devto-card-number-luhn
and since i am here, the same site now has wedding invitation cards at https://invite.theomnikit.com/?utm_source=devto&utm_medium=post&utm_campaign=devto-card-number-luhn if anyone has a wedding coming up.
drafted this with some AI help, same as the guide. do you test with the gateway numbers or does your team still have someone's real card in a fixture somewhere




