Rails validation make sure your user passwords are strong

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

This entry was posted in RegEx, Ruby on Rails. Bookmark the permalink. Post a comment or leave a trackback: Trackback URL.

3 Comments

  1. Posted February 16, 2007 at 3:41 am | Permalink

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

  2. Posted September 29, 2007 at 9:01 pm | Permalink

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

  3. Posted January 6, 2009 at 4:42 am | Permalink

    I’ve wrote an article about generate random password before user has been saved
    Please take a look:
    http://railsgeek.com/2009/1/6/generate-random-password-in-rails

One Trackback

  1. [...] Vixiom Axioms » Rails validation make sure your user passwords are strong – [...]

Post a Comment

Your email is never published nor shared. Required fields are marked *

*
*

*
To prove you're a person (not a spam script), type the security word shown in the picture. Click on the picture to hear an audio file of the word.
Click to hear an audio file of the anti-spam word