Regular expressions make my head hurt
Tuesday, January 22nd, 2008A site to dull the pain Rubular. Via Ruby Inside.
A site to dull the pain Rubular. Via Ruby Inside.
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
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
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)’