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.
Then mask all but the last four digits.
That’s it! @card_masked will out put as ************2222




Like this post? subscribe to the feed.






Thank you! This is exactly what I’ve been looking for!
Comment by coolfactor — October 31, 2007 @ 11:20 pm