credit card number length
Hack to Learn: Validating Credit Card Numbers With Ruby (Part 1)
never fear
- Validating Credit Card Numbers With Ruby (Part 1)
Recently, while working on one of our client’s projects, I found myself needing to validate credit card numbers. Of course the most secure way to do it is to use your merchant services (i.e., Verisign PayFlowPro, etc.). However most often those services cost anywhere from $15/month and 3 cents per transaction and up.
For most purposes the business wants to simply prevent its customers from fat-fingering their credit card numbers when typing it in. But there are several pieces of information that can be validated for any given credit card like: expiration date, billing address, security code, cardholder’s name, etc.
For our purposes we simply wanted to protect customers from their own fat fingers. The Luhn algorithm does nicely for that purpose, and for the most part, keeps honest people honest.
Here it is using Ruby:
def validate_credit_card(number)reverse_card_num=@number.reversesum=0reverse_card_num.scan(/./).each_with_indexdo|digit,index|digit=digit.to_idigit*=2ifindex%2!=0ifdigit.to_s.length==2first_num=digit.to_s[0..0]second_num=digit.to_s[1..1]digit=first_num.to_i+second_num.to_iendsum+=digitendpass=sum%10==0?true:falseendTo use it just pass in your 15-16 digit credit card number and it will return a boolean for pass or fail.
When I have some more time I’ll post some additional validation code that CBCI currently uses for credit cards.