Mask Credit Card Numbers with Regular Expressions in Rails

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

This entry was posted in RegEx, Ruby on Rails. Bookmark the permalink. Post a comment or leave a trackback: Trackback URL.

One Comment

  1. Posted October 31, 2007 at 11:20 pm | Permalink

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

Post a Comment

Your email is never published nor shared. Required fields are marked *

*
*

*
To prove you're a person (not a spam script), type the security word shown in the picture. Click on the picture to hear an audio file of the word.
Click to hear an audio file of the anti-spam word