Once I had to create a screen for entering credit card numbers and one thing I’ve found useful is the number validation. It is quite well explained in Wikipedia. I’ve used the implementation written in Javascript and created a small CC number validation page.
The main part is here:
String.prototype.luhnCheck = function() { var luhnArr = [[0,2,4,6,8,1,3,5,7,9],[0,1,2,3,4,5,6,7,8,9]], sum = 0; this.replace(/\D+/g,"").replace(/[\d]/g, function(c, p, o){ sum += luhnArr[ (o.length-p)&1 ][ parseInt(c,10) ]; }); return (sum%10 === 0) && (sum > 0); };
And the whole page source:
<html> <head> <title>Credit Card Number Validator</title> <style type="text/css"> .error { color: red; background-image:url('http://www.webcou.com/images/icon-no.gif'); background-repeat:no-repeat; background-position:left middle; padding-left: 20px; } .success { color: green; background-image:url('http://www.webcou.com/images/icon-yes.gif'); background-repeat:no-repeat; background-position:left middle; padding-left: 20px; } </style> <script type="text/javascript"> <!-- function checkCC( ccNumberId, ccNumberMessageId ) { var ccNumberMessage = document.getElementById( ccNumberMessageId ); var ccNumber = document.getElementById( ccNumberId ); if ( ccNumber.value.length == 0 ) { ccNumberMessage.textContent = ""; } else { var isValid = 'valid'; if ( ccNumber.value.luhnCheck() ) { ccNumberMessage.textContent = 'CC Number is valid'; ccNumberMessage.className = 'success'; } else { ccNumberMessage.textContent = 'CC Number is not valid'; ccNumberMessage.className = 'error'; } } } String.prototype.luhnCheck = function() { var luhnArr = [[0,2,4,6,8,1,3,5,7,9],[0,1,2,3,4,5,6,7,8,9]], sum = 0; this.replace(/\D+/g,"").replace(/[\d]/g, function(c, p, o){ sum += luhnArr[ (o.length-p)&1 ][ parseInt(c,10) ]; }); return (sum%10 === 0) && (sum > 0); }; --> </script> </head> <body> <form name="ccData"> <fieldset> <legend>Credit Card Number Validator</legend> <label for="ccNumber">Enter CC Number:</label> <input id="ccNumber" name="ccNumber" type="text" onblur="checkCC(this.id, 'ccNumberMessage')"> <span id="ccNumberMessage"><span> </fieldset> </form> </body> </html>
You can also test how it works live: http://blog.vilutis.lt/try/luhn.html
Now I can delete it from my desktop 🙂
Validuoja “werwe34” kaip valid CC numberi 😉
Reiškia netikrina ilgio 🙂
Įdomu, gaunasi, kad netikrinam ilgio, tikrinam tik skaičius, o 34, 3434 ar 3434343434 t.y. bet koks “34” pasikartojimas gaunasi tinkamas 🙂
Na realiai dar galima būtų pridėti ilgio tikrinimą, kur pamatytum, kad “34” pradžia galima tik American Express kortelėms, kurių numberio ilgis yra 15 ir “3434343…” nebebūtų validu.
Čia tik pavyzdys juk 😉