Vixiom Axioms

August 12, 2006

Rails validation make sure your user passwords are strong

Filed under: RegEx, Ruby on Rails Alastair @ 10:04 am

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)’

Digg! submit Rails validation make sure your user passwords are strong to stumbleupon.com submit Rails validation make sure your user passwords are strong to del.icio.us submit Rails validation make sure your user passwords are strong to reddit.com Like this post? subscribe to the feed.

3 Comments »

  1. validates_format_of :password, /^(?=.*\d)(?=.*[a-z])(?=.*[A-Z])(?!.*\s).{8,15}$/

    Comment by Hank — February 16, 2007 @ 3:41 am

  2. […] Vixiom Axioms » Rails validation make sure your user passwords are strong - […]

    Pingback by GeoLabs » Links for January 31st through June 26th — June 27, 2007 @ 1:58 pm

  3. I think the dot(.) in the funky char set must be escaped (like \.).

    Comment by mb — September 29, 2007 @ 9:01 pm

RSS feed for comments on this post. TrackBack URL

Leave a comment

*
To prove you're a person (not a spam script), type the security word shown in the picture.
Anti-Spam Image

Powered by WordPress