Vixiom Axioms

September 14, 2006

Mask Credit Card Numbers with Regular Expressions in Rails

Filed under: RegEx, Ruby on Rails Alastair @ 10:03 am

Sometimes you need to display sensitive information in a browser, such as the credit card a customer has on file. Obviously you don’t want to show the entire card number in case the customer leaves there browser open on a public computer, or even worse someone hacks into their account. However, you do need to show a piece of the information otherwise the customer would have no idea which credit card was on file. How to mask the credit card number? Regular Expressions to the rescue!

When I first searched for a way to do this I was surprised that I couldn’t find any examples, there’s a ton of regex tutorials for checking if emails are valid but none for masking credit card numbers. Here’s my solution in Rails.

Let’s say the customer’s card number is 5555-4444-3333-2222 (@customer.card_number = 5555-4444-3333-2222). First strip everything but the numbers.

    card_masked ||= @customer.card_number.gsub(/[^0-9]/, )

Then mask all but the last four digits.

    @card_masked = card_masked.sub(/^([0-9]+)([0-9]{4})$/) { ‘*’ * $1.length + $2 }

That’s it! @card_masked will out put as ************2222

Digg! submit Mask Credit Card Numbers with Regular Expressions in Rails to stumbleupon.com submit Mask Credit Card Numbers with Regular Expressions in Rails to del.icio.us submit Mask Credit Card Numbers with Regular Expressions in Rails to reddit.com Like this post? subscribe to the feed.

1 Comment »

  1. Thank you! This is exactly what I’ve been looking for!

    Comment by coolfactor — October 31, 2007 @ 11:20 pm

RSS feed for comments on this post. TrackBack URL

Leave a comment

*
To prove you're a person (not a spam script), type the security word shown in the picture.
Anti-Spam Image

Powered by WordPress