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 written by
Alastair, posted on
September 14, 2006 at 10:03 am, filed under
RegEx,
Ruby on Rails. Bookmark the
permalink. Follow any comments here with the
RSS feed for this post.
or leave a trackback:
Trackback URL.
© Copyright 2006 - 2012 Alastair Dawson
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
One Comment
Thank you! This is exactly what I’ve been looking for!