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

5 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

  4. Mats Gard
    Posted April 14, 2010 at 2:03 am | Permalink

    The “funky charcters” only include whitespace, another solution to ONLY allow \da-zA-Z, would be like this:
    ^(?=\d)(?=.*[a-z])(?=.*[A-Z])(?!.*[^\da-zA-Z]).{8,15}$

    If you need to add allowed characters (but not required) you could for example add ‘+’ like this:
    ^(?=\d)(?=.*[a-z])(?=.*[A-Z])(?!.*[^\da-zA-Z\+]).{8,15}$

  5. Mats Gard
    Posted April 14, 2010 at 2:52 am | Permalink

    Sorry, I forgot .* before \d in my last post, it should be like this:
    ^(?=.*\d)(?=.*[a-z])(?=.*[A-Z])(?!.*[^\da-zA-Z]).{8,15}$

    Thanks:
    http://www.rubular.com/

One Trackback

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

Post a Comment

Your email is never 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