Archive for the ‘RegEx’ Category

Regular expressions make my head hurt

Tuesday, January 22nd, 2008

A site to dull the pain Rubular. Via Ruby Inside.

Mask Credit Card Numbers with Regular Expressions in Rails

Thursday, September 14th, 2006

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

Rails validation make sure your user passwords are strong

Saturday, August 12th, 2006

Most user created passwords are astoundingly weak (’12345′, ‘mypass’). How do you make them stronger? Don’t give them a choice!

Here’s how to validate a password in RoR to make sure it’s strong using a regular expression (regex).
In your model add a custom validate method (after the regular validation) that adds an error unless the password is valid.

The ‘password_validate?’ method

def password_valid? self.password =~ /^(?=.*d)(?=.*[a-z])(?=.*[A-Z])(?!.*s).{8,15}$/ end

In this case the regular expression /^(?=.*\d)(?=.*[a-z])(?=.*[A-Z])(?!.*\s).{8,15}$/ is checking that the password is 8-15 characters long ‘.{8,15}’, and it contains at least one uppercase letter ‘(?=.*[A-Z])’ and one digit ‘(?=.*\d)’. Actually it also checks for at least one lowercase letter as well ‘(?=.*[a-z])’ but most users usually include that, it also checks that there’s no funky characters ‘(?!.*\s)’